我希望能够应用DRY,并且在构建jinja2模板时不必重复自己。因此,我希望能够从动态构造的变量名中引用jinja2模板中的变量,例如:
{% for a in [ 'a', 'b', 'c'] %}
{% set name = a + "_name" %}
{% set value = {{ name }} %}
hello there {{ value }}
{% endfor %}jinja中的输入变量应该是
a_name = 1
b_name = 2
c_name = 3我的结果就是
hello there 1
hello there 2
hello there 3这个是可能的吗?
我知道我只需要将一个数据结构传入jinja2来做类似的事情,但是我不能随意修改模板中的内容。
发布于 2015-07-31 15:35:35
我从here那里得到了答案
基本上,定义一个contextfunction并在jinja代码中引用它:
from jinja2 import Environment, FileSystemLoader, contextfunction
j2_env = Environment( loader=FileSystemLoader(directory), trim_blocks=False )
this_template = j2_env.get_template( """
{% for i in [ 'a', 'b', 'c'] %}
hello there {{ context()[i+"_name"] }}
{% endfor %}
""" )
@contextfunction
def get_context(c):
return c
this_template.globals['context'] = get_context
this_template.render( **{ 'a_name': 1, 'b_name': 2, 'c_name': 3 } )https://stackoverflow.com/questions/31713271
复制相似问题