Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a variable in a child template in Jinja2?

Tags:

python

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

like image 708
101010 Avatar asked Oct 24 '25 03:10

101010


1 Answers

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 %}
like image 87
101010 Avatar answered Oct 26 '25 16:10

101010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!