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 explain this is a test case:

File t1.djhtml :

<root>
    <block t3_container>
        {% block t3 %}This should be 'CONTENT'{% endblock %}
    </block t3_container>

    <block t2_container>
    {% block t2 %}{% endblock %}
    </block t2_container>
</root>

File t2.djhtml :

{% extends 't1.djhtml' %}

{% block t2 %}
        <block t2>
            {%- include 't3.djhtml' with context %}
        </block t2>
{% endblock %}

File t3.djhtml :

{% block t3 %}
        <block t3>
            CONTENT
        </block t3>
{% endblock %}

File test.py :

from jinja2 import Environment, FileSystemLoader
env  = Environment(loader=FileSystemLoader(''))
t=env.get_template('t2.djhtml')
print t.render()

The output is:

<root>
    <block t3_container>
        This should be 'CONTENT'
    </block t3_container>

    <block t2_container>

        <block t2>
        <block t3>
            CONTENT
        </block t3>

        </block t2>

    </block t2_container>
</root>

The t2 block should be empty, and t3_container should have block t3 's content inside. How do I accomplish this?


要回答我自己的问题,您可以在包含的文件中使用宏,但不要将其包含在内,而是使用上下文导入宏。

//File T1
<root>
  <block t3_container>
    {% block t3 %}{% endblock %}
  </block t3_container>

  <block t2_container>
  {% block t2 %}{% endblock %}
  </block t2_container>
</root>

// File T2
{% extends 't1.djhtml' %}
{%- from 't3.djhtml' import inner, inner2 with context %}

{% block t3 %}
   {{inner2()}}   
{% endblock %}

{% block t2 %}
    <block t2>
        {{ inner() }}
    </block t2>
{% endblock %}

// File T3
{% macro inner2() %}
    <block t3>
        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.djhtml')
print t.render({ 'foo' : 122 })
链接地址: http://www.djcxy.com/p/58092.html

上一篇: ImageView:填充水平维持高宽比

下一篇: 在jinja2中为包含父文件的文件使用块