Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variables from child template to parent in Jinja2

Tags:

I want to have one parent template and many children templates with their own variables that they pass to the parent, like so:

parent.html:

{% block variables %} {% endblock %}  {% if bool_var %}     {{ option_a }} {% else %}     {{ option_b }} {% endif %} 

child.html:

{% extends "parent.html" %}  {% block variables %}     {% set bool_var = True %}     {% set option_a = 'Text specific to this child template' %}     {% set option_b = 'More text specific to this child template' %} {% endblock %} 

But the variables end up undefined in the parent.

like image 433
Nathron Avatar asked Jul 18 '14 20:07

Nathron


People also ask

Which 3 features are included in the Jinja2 templates?

Some of the features of Jinja are: sandboxed execution. automatic HTML escaping to prevent cross-site scripting (XSS) attacks. template inheritance.

How do you write a for loop in Jinja2?

Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.

What is the Jinja2 delimiters for expressions to print to the template output?

The default Jinja delimiters are configured as follows: {% ... %} for Statements. {{ ... }} for Expressions to print to the template output. {# ... #} for Comments not included in the template output.


1 Answers

Ah. Apparently they won't be defined when they are passed through blocks. The solution is to just remove the block tags and set it up like so:

parent.html:

{% if bool_var %}     {{ option_a }} {% else %}     {{ option_b }} {% endif %} 

child.html:

{% extends "parent.html" %}  {% set bool_var = True %} {% set option_a = 'Text specific to this child template' %} {% set option_b = 'More text specific to this child template' %} 
like image 179
Nathron Avatar answered Sep 25 '22 02:09

Nathron