【问题标题】:Referencing jinja2 variable from a variable从变量中引用 jinja2 变量
【发布时间】:2015-10-21 04:34:50
【问题描述】:

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

【问题讨论】:

    标签: variables jinja2


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2015-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-08
      • 2016-01-03
      • 2022-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多