Create Jinja2 macros that place content in different places

I want to create a table of contents and endnotes in a Jinja2 template. How to complete these tasks?

For example, I want to have the following template:

 {% block toc %}
 {# ... the ToC goes here ... #}
 {% endblock %}

 {% include "some other file with content.jnj" %}

 {% block endnotes %}
 {# ... the endnotes go here ... #}
 {% endblock %}

Where some other file with content.jnjhas such content:

{% section "One" %}
Title information for Section One (may be quite long); goes in Table of Contents
...
Content of section One

{% section "Two" %}
Title information of Section Two (also may be quite long)

<a href="#" id="en1">EndNote 1</a> 
<script type="text/javsacript">...(may be reasonably long)
</script> {# ... Everything up to here is included in the EndNote #}

Where I say "can be quite / reasonably long", I want to say that it cannot be quoted as an argument for a macro or global function.

I am wondering if there is a sample for this that can accommodate this, as part of Jinja2.

My initial thought is to create an extension so that you can have a block for sections and end notes, for example:

{% section "One" %}
Title information goes here.
{% endsection %}

{% endnote "one" %}
<a href="#">...</a>
<script> ... </script>
{% endendnote %}

Then the global functions are performed (which pass in the Jinja2 environment):

{{ table_of_contents() }}

{% include ... %}

{{ endnotes() }}

However, although this will work for endnotes, I assume a second pass is required for the table of contents.

. .

+3
1

, (, , , ). Python, Jinja / ? .

content.jnj:

{% set sections = [] %}
{% do sections.append({
'title': 'Section One title',
'body': 
"""
Section one main body text...
""",
'endnotes': 
"""
<a href='#'>...</a>
<script> ... </script>
""",
})
%}
{# append more sections #}

template.jnj:

{% from 'content.jnj' import sections as sections %}
{# table of contents #}
{% for section in sections %}
    {{ loop.index }}. {{ section['title'] }}
{% endfor %}
{# body #}
{% for section in sections %}
    {{ section['title'] }}
    {{ section['body'] }}
{% endfor %}
{# endnotes #}
{% for section in sections %}
    {{ loop.index }}. {{ section['endnotes'] }}
{% endfor %}

, content.jnj , Jinja2 do (, env = jinja2.Environment(extensions=['jinja2.ext.do']).)

, - , reStructuredText, Sphinx (Jinja2 - ).

+2

Source: https://habr.com/ru/post/1746240/


All Articles