2014-07-18 60 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) 
相關問題