将自定义过滤器定义嵌入jinja2模板? [英] Embed custom filter definition into jinja2 template?

查看:42
本文介绍了将自定义过滤器定义嵌入jinja2模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些Jinja2模板,希望能够在切向相关的项目中尽可能轻松地重用.我有一组自定义便捷过滤器,我希望模板随它们一起携带".是否有Jinja2语法可将过滤器定义嵌入模板本身?还是将任何类型的纯Python函数嵌入到Jinja2模板中的机制,可以对传递到模板中的变量起作用?我曾经使用过mako,这样做很简单,但是由于缺少自定义语法,因此在mako中对LaTeX进行模板非常痛苦,因此我不得不进行切换.

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.

推荐答案

您可以采用 NO 方法将python直接嵌入Jinja2模板,我知道的方法是在应用程序中定义并将它们添加到您的Jinja2环境实例中.就像下面的示例一样,该示例取自 https://jinja.palletsprojects.com/zh/2.11.x/api/#writing-filters .

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 }}

结果是这个

TESTING

这篇关于将自定义过滤器定义嵌入jinja2模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆