2014-07-18 62 views
14

我想有一个父模板和许多孩子用自己的变量的模板,他们传递给家长,像这样:变量传给父母在Jinja2的

parent.html:

{% block variables %} 
{% endblock %} 

{% if bool_var %} 
    {{ option_a }} 
{% else %} 
    {{ option_b }} 
{% endif %} 

child.html:

{% extends "parent.html" %} 

{% block variables %} 
    {% set bool_var = True %} 
    {% set option_a = 'Text specific to this child template' %} 
    {% set option_b = 'More text specific to this child template' %} 
{% endblock %} 

但变量都未定义父。

回答

15

啊。显然,当它们通过块时,它们将不会被定义。解决的办法是只删除块标记,并设置它就像这样:

parent.html:

{% if bool_var %} 
    {{ option_a }} 
{% else %} 
    {{ option_b }} 
{% endif %} 

child.html:

{% extends "parent.html" %} 

{% set bool_var = True %} 
{% set option_a = 'Text specific to this child template' %} 
{% set option_b = 'More text specific to this child template' %} 
+0

我'parent.html '不直接我们e我的'bool_var',而是有一个'include'语句,它包含另一个使用'bool_var'的模板。在这个包含的模板中,该变量直到在'parent.html'文件中才出现undefined,或者使用了诸如“{{bool_var}}”之类的变量或者使用了重言式的“{%set bool_var = bool_var%}”。 – tremby

0

如果Nathron的解决方案不解决您的问题,您可以将函数与全局python变量结合使用以传递变量值。

  • 优点:该变量的值将在所有模板中可用。您可以在块内设置变量。
  • 缺点:更多的开销。

这是我做过什么:

child.j2:

{{ set_my_var('new var value') }} 

base.j2

{% set my_var = get_my_var() %} 

Python代码

my_var = '' 


def set_my_var(value): 
    global my_var 
    my_var = value 
    return '' # a function returning nothing will print a "none" 


def get_my_var(): 
    global my_var 
    return my_var 

# make functions available inside jinja2 
config = { 'set_my_var': set_my_var, 
      'get_my_var': get_my_var, 
      ... 
     } 

template = env.get_template('base.j2') 

generated_code = template.render(config) 
相关问题