Question

I am just starting out with jinja2 template library. I can't figure out how to fill content in a block of parent template from included child template. For example I have a parent template-

t-1:

<div id="includedTemplateName>
    {% block includedTemplateName %}{% endblock %}
</div>

<div id="content">
    {% include 't-2.htm' %}
</div>

and child template

t-2:

<div>
conten
</div>
{% block includedTemplateName %}t-2{% endblock %}

I want value in div with id includedTemplateName to be 't-2' as defined in t-2. How can I achieve this with jinja2?

Was it helpful?

Solution

You're confusing the include statement with template inheritance. The include statement is useful to include a template and return the rendered contents of that file into the current namespace (from Jinja2 docs). Your "child" template is already rendered when it's included, so there isn't any way for it to change values in your parent.

You need to use template inheritance.

t1.html:

<div id="includedTemplateName">
    {% block includedTemplateName %}{% endblock %}
</div>

<div id="content">
    {% block content %}{% endblock %}
</div>

t2.html:

{% extends "t1.html" %}
{% block includedTemplateName %}t-2{% endblock %}
{% block content %}content{% endblock %}

From the Jinja2 docs:

The {% extends %} tag is the key here. It tells the template engine that this template “extends” another template. When the template system evaluates this template, first it locates the parent. The extends tag should be the first tag in the template. Everything before it is printed out normally and may cause confusion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top