flask - 如何将变量传递给未呈现的 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
而不被渲染?
解决方案
@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'])
.
推荐阅读
- javascript - 如何维护一个最大长度的字符串列表,当新字符串进来时删除第一个
- uniqueidentifier - 将公钥转换为用户目录路径的最佳算法?
- python-3.x - 在 lambda 函数中为字符串省略 Nans
- javascript - a11y & angularjs - Windows 屏幕阅读器覆盖 keydown 事件
- python - 我如何通过 webhook 发送 python 变量
- amazon-web-services - 使用 AWS Kinesis Data Analytics 使用 DynamoDB 流
- python-3.x - PCA 分析中的纯度分数低于预期
- xcode - 更新 Circle CI 上的 fastlane 版本
- vim - 我的 vim ui 很奇怪。很难用文字解释,请看图
- python - 哪个元类用于创建具有多个基的类?