Development guide¶
Jinja2 extensions for Moban¶
Since version 0.2, mobanfile supports an extra field plugin_dir, along with template_dir. When you put your own jinja2 filters, tests and globals in your moban repo, you can let moban know about them via this keyword.
Importantly, you have to have __init__.py file in your plugin_dir. Otherwise, your plugins will NOT be loaded.
Jinja2 Filter¶
from moban.extensions import JinjaFilter
@JinjaFilter()
def repr(string):
if isinstance(string, list):
return ["'{0}'".format(str(element)) for element in string]
else:
return "'{0}'".format(str(string))
Jinja2 Test¶
from os.path import isdir, isfile, isabs, exists
from os.path import lexists, islink, samefile, ismount
from moban.extensions import jinja_tests
jinja_tests(
is_dir=isdir,
directory=isdir,
is_file=isfile,
file=isfile,
is_link=islink,
link=islink,
exists=exists,
link_exists=lexists,
# path testing
is_abs=isabs,
abs=isabs,
is_same_file=samefile,
same_file=samefile,
is_mount=ismount,
mount=ismount,
)
Jinja2 Globals¶
def test_globals():
output = "globals.txt"
test_dict = dict(hello="world")
jinja_global("test", test_dict)
path = os.path.join("tests", "fixtures", "globals")
engine = Engine([path], path)
engine.render_to_file("basic.template", "basic.yml", output)
with open(output, "r") as output_file:
content = output_file.read()
eq_(content, "world\n\ntest")
os.unlink(output)
It is possible to write an installable package including your own jinja2 filters, tests and globals. Please email me for more details.
Template engine extension for Moban¶
moban version 0.2 started using lml to employ loose couple plugins. Other template engines, such as marko, haml can be plugged into moban seamless.
In order plugin other template engines, it is to write a lml plugin. The following is an example starting point for any template engine.
from lml.plugin import PluginInfo
from moban.constants import TEMPLATE_ENGINE_EXTENSION
@PluginInfo(TEMPLATE_ENGINE_EXTENSION, tags=["mako"])
class MakoEngine:
pass
After you will have finished the engine plugin, you can either place it in plugin_dir in order to get it loaded, or make an installable python package. In the latter case, please refer to yehua: doing that in less than 5 minutes.