例如,我有模板 index.html 和 custom_jinja2_filter
<h1> My name is {{ name }} </h1>
<h2> I'm {{ year }} years old </h2>
<p> I'd like to pass template context to custom
filter like single object. Is it possible?
{{ ??? | custom_jinja2_filter }}
</p>
def custom_jinja2_filter(context):
name = context['name']
year = context['year']
答案 0 :(得分:2)
您可以将当前上下文传递给使用@contextfunction
标记为可调用的函数:
from jinja2 import contextfunction
@contextfunction
def custom_jinja2_filter(context):
name = context.name
year = context.year
return '(c) {} {}'.format(year, name)