在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 %}

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

拿特隆

啊。显然,当它们通过块传递时将不会被定义。解决方案是仅删除块标签并按如下所示进行设置:

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' %}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章