首页 > 解决方案 > 如何将变量传递给未呈现的 Jinja 模板?

问题描述

我正在为一本有很多章节的书编写一个烧瓶应用程序。在索引页面上,我有每个章节的链接:<a href="/chapters/{{ chapter }}">{{ chapter }}</a>. 我渲染每一章的功能是:

@app.route("/chapters/<chapter>")
def chapter(chapter):
    return render_template(f"chapters/{chapter}.html", chapter=chapter)

我将章节的布局和正文分开。所以我chapter.html包括布局并有一个实际内容的块:

{% include "layout.html" %}

{% block chapter %}{% endblock %}
...

虽然类似chapter-1.html扩展chapter.html并包含本书的实际文本。但现在我想要有按钮chapter.html,允许用户转到上一章/下一章。有没有办法让我将chapter变量从函数传递到模板chapter.html而不被渲染?

标签: flaskjinja2

解决方案


@app.route("/chapters/<chapter>")
def chapter(chapter):
    session['chapter'] = chapter
    return render_template(f"chapters/{chapter}.html", chapter=chapter)

使用 CSS 设置<a>标签样式,使其看起来像一个按钮,并将章节存储在会话中。

<a href="{{ url_for( 'chapter', chapter=session['chapter'] - 1) }}" class="button-style">Previuos</a>

对于下一章:

<a href="{{ url_for( 'chapter', chapter=session['chapter'] + 1) }}" class="button-style">Next</a>

如果您的章节值是字符串,请使用chapter=int(session['chapter']).


推荐阅读