使用 Jinja 渲染原始字符串

Render a raw string with Jinja

我有一个字符串,我想将其视为 Jinja 模板。我尝试返回字符串,但它按原样发送,Jinja 不呈现它。我不想制作一个模板文件来用 render_template 渲染它。如何使用 Jinja 渲染字符串?

@app.route('/results')
def results():
    template = '''<div class="results">
        {% for option in options() %}
            <p>{{ option }}</p>
        {% endfor %}
    </div>
    '''
    return template

您正在寻找 render_template_string.

flask.render_template_string(source, **context)

Renders a template from the given template source string with the given context.

Parameters:

  • source – the sourcecode of the template to be rendered
  • context – the variables that should be available in the context of the template.
from flask import render_template_string

在您的 HTML 字符串上调用它来呈现它,并 return 结果。

return render_template_string(template)