在Jinja2中将变量从子模板传递给父模板

Nat*_*ron 19 jinja2

我希望有一个父模板和许多子模板,它们有自己的变量传递给父模板,如下所示:

parent.html:

{% block variables %}
{% endblock %}

{% if bool_var %}
    {{ option_a }}
{% else %}
    {{ option_b }}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

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 %}
Run Code Online (Sandbox Code Playgroud)

但变量最终在父级中未定义.

Nat*_*ron 24

啊.显然,当它们通过块时,它们将不会被定义.解决方案是删除块标记并将其设置如下:

parent.html:

{% if bool_var %}
    {{ option_a }}
{% else %}
    {{ option_b }}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

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' %}
Run Code Online (Sandbox Code Playgroud)