Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

python - Embed custom filter definition into jinja2 template?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...