Use Blocks From Included Files For Parent In Jinja2
I'm not sure if what I want to do is possible: I'm trying to get a block in a parent template to be filled out by a file included in a child template of the parent. The best way to
Solution 1:
You can use macros in the included file, but instead of including it, you import the macros with context.
T1.html
<root><blockt3_container>
    {% block t3 %}{% endblock %}
  </block t3_container>
  <blockt2_container>
  {% block t2 %}{% endblock %}
  </block t2_container>
</root>T2.html
{% extends 'T1.html' %}
{%- from 'T3.html' import inner, inner2 with context %}
{% block t3 %}
    {{ inner2() }}   
{% endblock %}
{% block t2 %}
    <blockt2>
        {{ inner() }}
    </block t2>
{% endblock %}
T3.html
{% macro inner2() %}
    <blockt3>
        CONTENT '{{ foo+1 }}'
    </block t3>
{% endmacro %}
{% macro inner() %}
  hello
{% endmacro %}
test.py
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader("."))
t = env.get_template("T2.html")
print(t.render({"foo": 122}))
Post a Comment for "Use Blocks From Included Files For Parent In Jinja2"