Skip to main content
 首页 » 编程设计

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

2025年05月04日18zhwl

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

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

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

请您参考如下方法:

您可以加载 Template , 而不是使用 Jinja2 的 Environment.get_or_select_template 渲染它Flask.jinja_env 上的方法.一旦你有了模板,如果你不渲染它,你可以访问模板的 block :

some-email.html

{% block subject %}This is the subject: {{ subject_details }}{% endblock %} 
{% block body %} 
This is the body. 
 
Hello there, {{ name }}! 
{% endblock %} 

电子邮件处理程序.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