问题
I'm writing some Jinja2 templates that I'd like to be able to reuse as painlessly as possible in tangentially related projects. I have a set of custom convenience filters that I'd like the templates to "carry around" with them. Is there a Jinja2 syntax for embedding filter definitions into a template itself? Or a mechanism for embedding any kind of pure Python function into a Jinja2 template that can act on variables passed into the template? I used to use mako, and there it was trivial to do this, but templating LaTeX in mako is painful because of the lack of custom syntax, so I had to make the switch.
回答1:
There is NO way you can embed python directly into a Jinja2 Template, the way that I know of is to define in your application and add them to your Jinja2 environment instance. Like the following example taken from https://jinja.palletsprojects.com/en/2.11.x/api/#writing-filters.
import jinja2
loader = jinja2.FileSystemLoader('/tmp')
env = jinja2.Environment(autoescape=True, loader=loader)
def upperstring(input):
"""Custom filter"""
return input.upper()
env.filters['upperstring'] = upperstring
temp = env.get_template('template.html')
temp.render(name="testing")
Here the Template I am using
{{ name | upperstring }}
Result is this
TESTING
来源:https://stackoverflow.com/questions/25449879/embed-custom-filter-definition-into-jinja2-template