When you define the helper function of a template engine, you may want to use it directly from outside the template. For mako, use get_def.
$ pip install mako
The method of rendering by directly specifying the character string is as follows.
# -*- coding:utf-8 -*-
from mako.template import Template
template = Template(u"""\
hello ${name}
""")
print(template.render(name="world"))
# hello world
The method to call the helper function defined in another place from another place (show.html) is as follows. When the file structure is as follows.
$ tree
.
|-- greeting.html
|-- hello_with_otherfile.py
`-- show.html
Register the top-level path used when searching for a template in Template Lookup. And it calls hello of greeting.html through the show.html template.
hello_with_otherfile.py
# -*- coding:utf-8 -*-
from mako.lookup import TemplateLookup
import os.path
here = os.path.abspath(os.path.dirname(__file__))
lookup = TemplateLookup([here])
template = lookup.get_template("show.html")
print(template.render(name="world"))
# hello world
show.html
<%namespace file="./greeting.html" name="g"/>
${g.hello(name)}
greeting.html
<%def name="hello(name)">
hello ${name}
</%def>
Finally the main subject. How to use the render function defined in .mako directly in mako. In this case, the hello function defined in greeting.html is the function you want to use. This uses get_def as follows.
# -*- coding:utf-8 -*-
from mako.lookup import TemplateLookup
import os.path
here = os.path.abspath(os.path.dirname(__file__))
lookup = TemplateLookup([here])
hello = lookup.get_template("greeting.html").get_def("hello")
print(hello.render("world"))
# hello world
Recommended Posts