Adnan
Adnan

Reputation: 613

Use Parts of a Template file in Jinja 2

So I want to create a send email function using Templates with Jinja 2. My specific Issue is that I want to create one template for an email which contains both the subject and the body of the email. For example my template can look like

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

but I need the subject and body to be saved in different variables to be passed to the sendmail function. My question is , how can I use a single template file and render parts of it in different variables.

Upvotes: 2

Views: 1305

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159865

You can load a Template, rather than rendering it by using Jinja2's Environment.get_or_select_template method on Flask.jinja_env. Once you have the template, you can access the template's blocks if you don't render it:

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

Upvotes: 1

Related Questions