简体   繁体   English

如何在Jinja2的子模板中设置变量?

[英]How to set a variable in a child template in Jinja2?

This question was asked once , but it didn't answer the question, so I'm re-asking it directly. 这个问题被问过一次 ,但是没有回答,所以我直接向它提问。

I'm trying to set a variable in a child template, so that it changes how a parent template renders things. 我正在尝试在子模板中设置一个变量,以便它更改父模板呈现事物的方式。 In this question, I show a practical example. 在这个问题上,我给出一个实际的例子。

My site has 2 kinds of templates. 我的网站有2种模板。 One that displays the content narrow and a full width template. 一个显示内容狭窄和全宽模板的模板。

(I snipped out all the complexity so that I can show you a simple example) (我删除了所有复杂性,以便向您展示一个简单的示例)

page.html page.html中

{% extends "base.html" %}

{% block content %}
        <div id="pageContentContainer">
            <div class="row">
            {% if fullwidth %}
                <div class="col-12">fffff
                    {{super()}}
                </div>
            {% else %}
                <div class="col-9">
                    {{super()}}
                </div>
            {% endif %}
            </div>
        </div>
{% endblock %}  

page-fullwidth.html 页面fullwidth.html

{% extends "page.html" %}

{% block content %}
    {% set fullwidth = true %}
    {{super()}}
{% endblock %}

This doesn't work. 这行不通。 The variable fullwidth is not True in the parent template. 父模板中的变量fullwidth不是True。

Is there some other practical way to do this? 还有其他可行的方法吗? I don't want to repeat the contents of page.html in page-fullwidth.html . 我不想在page-fullwidth.html重复page.html的内容。 (In the real one, this file is more complex.) (实际上,此文件更复杂。)

Almost right. 差不多了 This is the answer. 这就是答案。 The variable setter needs to be outside the block 变量设置器必须在程序段之外

page-fullwidth.html 页面fullwidth.html

{% extends "page.html" %}

{% set fullwidth = true %}

{% block content %}
    {{super()}}
{% endblock %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM