从变量引用jinja2变量

时间:2015-07-30 00:16:26

标签: variables jinja2

我希望能够应用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来做类似的事情,但我不能随意修改模板中的内容。

1 个答案:

答案 0 :(得分:0)

我从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 } )