Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use macros in the included file, but instead of including it, you import the macros with context.


T1.html

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

  <block t2_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 %}
    <block t2>
        {{ inner() }}
    </block t2>
{% endblock %}

T3.html

{% 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.html")

print(t.render({"foo": 122}))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...