Reputation: 6298
Is there any way use Django's templating system to render a template file and to return three discrete objects?
Use case: I'm putting together an email that is to be rendered based on some request parameters. Each email consists of a) a subject, b) a plain-text version, c) a html version. Ideally, I'd like to have all of these to be sourced from a single template file rather than three separate files, to make for easier maintenance.
Any ideas?
Upvotes: 0
Views: 974
Reputation: 34593
I would use render_to_string, passing in an argument of which section to render. That would allow you to use one template and render a portion of the template at a time.
from django.template.loader import render_to_string
subject = render_to_string('the-template.html',
{'section': 'subject', 'subject': 'Foo bar baz'})
plain_text = render_to_string('the-template.html',
{'section': 'text', 'text': 'Some text'})
html = render_to_string('the-template.html',
{'section': 'html', 'html': '<p>Some html</p>'})
#the-template.html
{% if section == 'subject' %}
{{ subject }}
{% elif section == 'text' %}
{{ plain_text }}
{% else %}
<h1>A headline, etc.</h1>
{{ html }}
{% endif %}
You can also pass whatever values you need from the incoming request to the template in the context.
Upvotes: 2