3

Jinja2 テンプレートで目次と文末脚注を作成したいと考えています。これらのタスクをどのように達成できますか?

たとえば、次のようなテンプレートが必要です。

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

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

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

には次のsome other file with content.jnjようなコンテンツがあります。

{% 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 #}

私が「かなり/適度に長いかもしれない」と言っているところでは、マクロまたはグローバル関数への引数として引用符で囲むことは合理的ではないと言っている.

Jinja2のフレームワーク内で、これに対応できるパターンがあるかどうか疑問に思っています。

私の最初の考えは、拡張機能を作成して、セクションとエンドノートのブロックを作成できるようにすることです。

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

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

次に、グローバル関数 (Jinja2 環境で渡す) を用意します。

{{ table_of_contents() }}

{% include ... %}

{{ endnotes() }}

ただし、これは文末脚注には機能しますが、目次には何かによる 2 回目のパスが必要になると思います。

読んでくれてありがとう。ご意見やご感想をお寄せいただければ幸いです。

ブライアン

4

1 に答える 1

2

各セクション (つまり、タイトル、本文、文末脚注) の一貫した構造を定義する上で、正しい道を進んでいるようです。この情報を、Jinja ブロックやカスタム拡張機能ではなく、通常の Python データ構造に格納することは許容されますか? 以下の例。

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.jnjJinja2do拡張機能を有効に する必要があることに注意してください(例: env = jinja2.Environment(extensions=['jinja2.ext.do']).)

やり過ぎかもしれませんが、コンテンツを reStructuredText などのマークアップ言語で保存し、プレゼンテーション レイヤーをSphinxテーマとして設計することもできます (Jinja2 がデフォルトのテンプレート形式です)。

于 2010-08-16T10:32:38.713 に答える