简体   繁体   中英

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. 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

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

{% extends "page.html" %}

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

This doesn't work. The variable fullwidth is not True in the parent template.

Is there some other practical way to do this? I don't want to repeat the contents of page.html in page-fullwidth.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

{% extends "page.html" %}

{% set fullwidth = true %}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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