python - Flask - 在没有模板的情况下使用 jinja 宏
问题描述
我有一个 Flask 应用程序,如下所示:
@app.route('/')
def index():
headline = render_template('headline.html', headline = 'xyz') #-> return <h1>xyz</h1>
return render_template('page.html', headline = headline) # insert headline html into a page
headline.html
是一个从宏文件 ( macros.html
) 中导入 jinja 宏的模板。宏生成标题。
headline.html
:
{% import 'macros.html' as macros %}
{{ macros.get_headline(headline) }}
macros.html
:
{% macro get_headline(headline) %}
<h1>{{ healine }}</h1>
{% endmacro %}
我的问题是 - 是否可以调用宏来获取headline
而不需要调用模板 headline.html
?
理想情况下,我想看看
@app.route('/')
def index():
headline = # somehow call get_headline('xyz') from macros.html
return render_template('page.html', headline = headline) # insert headline html into a page
解决方案
您可以从字符串中渲染模板,而不是从文件中渲染模板。所以你可以从一个字符串中调用你的宏。
from flask.templating import render_template_string
@app.route('/')
def index():
headline = render_template_string(
"{% import 'macros.html' as macros %}"
"{{ macros.get_headline(headline) }}",
headline='xyz'
)
return render_template('page.html', headline=headline)
(忽略错字healine
而不是headline
在macros.html中)
推荐阅读
- excel - Excel IFS 公式多条件
- java - 如何使用 java 8 流将用户列表保存到数据库
- maven - 我可以使用 Maven Shade 插件在单个 jar 文件中重新定位类而不做其他任何事情吗?
- python - 在字典中加载 .csv 文件并使用 Python 在列中搜索特定条目
- python-3.x - pkg_resources.DistributionNotFound: 'platformdirs<3,>=2' 分发未找到,virtualenv 需要它
- javascript - 如何使用来自 Joi 的验证?
- winforms - PictureBox 未在单击的标签上更新
- django - 外键的 Django ORM 过滤器逻辑给出了不清楚的结果
- arrays - PySpark:我们如何选择矩阵中取最高值的数据框?
- r - 使用xml2添加具有属性的子节点