Create Jinja2 macros that put content in separate places

Posted by Brian M. Hunt on Stack Overflow See other posts from Stack Overflow or by Brian M. Hunt
Published on 2010-05-19T17:58:15Z Indexed on 2010/05/19 18:00 UTC
Read the original article Hit count: 501

Filed under:
|

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

For example, I want to have a template as follows:

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

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

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

Where the some other file with content.jnj has content like this:

{% 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 "may be quite/reasonably long" I mean to say that it can't reasonably be put into quotes as an argument to a macro or global function.

I'm wondering if there's a pattern for this that may accommodate this, within the framework of Jinja2.

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

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

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

Then have global functions (that pass in the Jinja2 Environment):

{{ table_of_contents() }}

{% include ... %}

{{ endnotes() }}

However, while this will work for endnotes, I'd presume it requires a second pass by something for the table of contents.

Thank you for reading. I'd be much obliged for your thoughts and input.

Brian

© Stack Overflow or respective owner

Related posts about jinja2

Related posts about design-patterns