Python 在Jinja 2中使用模板文件的一部分
所以我想用Jinja2的模板创建一个发送电子邮件的功能。 我的具体问题是,我想为一封电子邮件创建一个模板,其中包含邮件的主题和正文。例如,我的模板可以是Python 在Jinja 2中使用模板文件的一部分,python,python-2.7,templates,jinja2,Python,Python 2.7,Templates,Jinja2,所以我想用Jinja2的模板创建一个发送电子邮件的功能。 我的具体问题是,我想为一封电子邮件创建一个模板,其中包含邮件的主题和正文。例如,我的模板可以是 Subject: This is the Subject Body: hello I am the body of this email 但是我需要将subject和body保存在不同的变量中,以传递给sendmail函数。我的问题是,如何使用单个模板文件并在不同变量中呈现部分模板文件。您可以加载一个模板文件,而不是在上使用Jinja2的方法
Subject: This is the Subject
Body: hello I am the body of this email
但是我需要将subject和body保存在不同的变量中,以传递给sendmail函数。我的问题是,如何使用单个模板文件并在不同变量中呈现部分模板文件。您可以加载一个模板文件,而不是在上使用Jinja2的方法来呈现它。拥有模板后,如果不渲染,则可以访问模板的块:
some-email.html
email_handler.py
{% block subject %}This is the subject: {{ subject_details }}{% endblock %}
{% block body %}
This is the body.
Hello there, {{ name }}!
{% endblock %}
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