在Jinja2中将变量从子模板传递给父模板 [英] Pass variables from child template to parent in Jinja2

查看:58
本文介绍了在Jinja2中将变量从子模板传递给父模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有一个父模板和许多子模板,这些子模板具有传递给父模板的变量,就像这样:

I want to have one parent template and many children templates with their own variables that they pass to the parent, like so:

parent.html:

parent.html:

{% block variables %}
{% endblock %}

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

child.html:

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

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

But the variables end up undefined in the parent.

推荐答案

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

Ah. Apparently they won't be defined when they are passed through blocks. The solution is to just remove the block tags and set it up like so:

parent.html:

parent.html:

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

child.html:

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

这篇关于在Jinja2中将变量从子模板传递给父模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆