{% for dict in list_of_dictionaries %}
{% block pick_dictionary_element %}
{% endblock %}
{% endfor %}
{% extends "parent.txt" %}
{% block pick_dictionary_element %}
{{ dict.a }}
{% endblock %}
{% extends "parent.txt" %}
{% block pick_dictionary_element %}
{{ dict.b }}
{% endblock %}
Then:
from jinja2 import Template, Environment, FileSystemLoader
e = Environment(loader=FileSystemLoader("./"))
e.get_template("child_one.txt").render(list_of_dictionaries=[{'a': 'a', 'b': 'b'}])
produces an empty output. How can I access the dict
var from the parent for loop? I kind of imagined jinja just in-lining the pick_dictionary_element
and the child having the for loop scope of its parent?
The key to what you are trying to do is to use the scoped
keyword on your block:
{# parent.txt #}
{% for dict in list_of_dictionaries %}
{% block pick_dictionary_element scoped %}
{% endblock %}
{% endfor %}
You made the mistake of using the name dict
in the loop:
{% for dict in list_of_dictionaries %}
The side effect of this was that the child template did not readily complain, since the symbol dict
exists in its context. If instead, you had done something like:
{# parent.txt #}
{% for a_dict in list_of_dictionaries %}
{% block pick_dictionary_element %}
{% endblock %}
{% endfor %}
{# child_one.txt #}
{% extends "parent.txt" %}
{% block pick_dictionary_element %}
{{ a_dict.a }}
{% endblock %}
You would have been told:
jinja2.exceptions.UndefinedError: 'a_dict' is undefined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With