例如,我有模板 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']
最佳答案
您可以将当前上下文传递给标记为可调用的函数 @contextfunction
:
from jinja2 import contextfunction
@contextfunction
def custom_jinja2_filter(context):
name = context.name
year = context.year
return '(c) {} {}'.format(year, name)
关于jinja2 在模板内的单个对象中获取整个上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42905444/