views:

69

answers:

2

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"?

+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
Seems to work. Thanks!
Mark
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
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