首页 > 解决方案 > 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

标签: pythonflaskjinja2

解决方案


您可以从字符串中渲染模板,而不是从文件中渲染模板。所以你可以从一个字符串中调用你的宏。

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中)


推荐阅读