Suppose my template has in it something like {% block subject %}my subject{% endblock %}
and I load this template with tmpl = loader.get_template('mytemplate.html')
, how can I extract "my subject"?
views:
69answers:
2
+1
A:
from django.template import Context
from django.template.loader import get_template
from django.template.loader_tags import BlockNode
t = get_template('template.html')
for node in t:
if isinstance(node, BlockNode) and node.name == 'subject':
print node.render(Context())
This worked for me, using Django 1.1.1
Camilo Díaz
2010-04-22 00:31:53
Seems to work. Thanks!
Mark
2010-04-22 04:35:14
A:
Camilo's solution doesn't work when your template extends a base. I've modified it a bit to (hopefully) fix that problem:
from django.template import Context
from django.template.loader import get_template
from django.template.loader_tags import BlockNode, ExtendsNode
def _get_node(template, context=Context(), name='subject'):
for node in template:
if isinstance(node, BlockNode) and node.name == name:
return node.render(context)
elif isinstance(node, ExtendsNode):
return _get_node(node.nodelist, context, name)
raise Exception("Node '%s' could not be found in template." % name)
I'm really not sure if this is the right way to recursively iterate over all the nodes... but it works in my limited case.
Mark
2010-07-08 00:46:58
Actually...just found an even better solution. Storing the email templates directly in the DB now. Makes em easier to edit, can store both HTML and Text versions in one entry (rather than 2 files), and I can add a field for subject as well.
Mark
2010-07-08 19:36:28