101010
101010

Reputation: 15756

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

Upvotes: 4

Views: 2488

Answers (1)

101010
101010

Reputation: 15756

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

Upvotes: 6

Related Questions