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

时间:2016-01-12 16:03:33

标签: python python-2.7 templates jinja2

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

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

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

1 个答案:

答案 0 :(得分:1)

您可以加载Template,而不是在Environment.get_or_select_template上使用Jinja2的Flask.jinja_env方法进行渲染。获得模板后,如果不进行渲染,则可以访问模板的块:

一些-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