在 Jinja 2 中使用部分模板文件

Use Parts of a Template file in Jinja 2

所以我想使用带有 Jinja 2 的模板创建发送电子邮件功能。 我的具体问题是我想为包含电子邮件主题和正文的电子邮件创建一个模板。例如我的模板可以看起来像

Subject: This is the Subject
Body: hello I am the body of this email

但我需要将主题和正文保存在不同的变量中以传递给 sendmail 函数。我的问题是,如何使用单个模板文件并在不同的变量中渲染它的一部分。

您可以加​​载 Template, rather than rendering it by using Jinja2's Environment.get_or_select_template method on Flask.jinja_env。一旦你有了模板,如果你不渲染它,你可以访问模板的块:

some-email.html

{% block subject %}This is the subject: {{ subject_details }}{% endblock %}
{% block body %}
This is the body.

Hello there, {{ name }}!
{% endblock %}

email_handler.py

def generate_email(template_name, **render_args):
    """Usage:
    >>> subject, body = generate_email(
            'some-email.html',
            subject_details="Hello World",
            name="Joe")
    """
    app.update_template_context(render_args)
    template = app.jinja_env.get_or_select_template(template_name)

    Context = template.new_context

    subject = template.blocks['subject'](Context(vars=render_args))
    body = template.blocks['body'](Context(vars=render_args))

    return subject, body

def send_email(template_name, **render_args):
    subject, body = generate_email(template_name, **render_args)
    # Send email with subject and body