Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How can I get a block from a template?

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

like image 402
mpen Avatar asked Apr 21 '10 23:04

mpen


People also ask

What does {{ this }} mean in Django?

These are special tokens that appear in django templates. You can read more about the syntax at the django template language reference in the documentation. {{ foo }} - this is a placeholder in the template, for the variable foo that is passed to the template from a view.

How do I loop a list through a template in Django?

The syntax of the Django template language involves four constructs: {{ }} and {% %} . In this shot, we will look at how to use a for loop in Django templates. The for template in Django is commonly used to loop through lists or dictionaries, making the item being looped over available in a context variable.

What does {% endblock %} mean?

{% endblock %} </div> </body> </html> In this example, the {% block %} tags define four blocks that child templates can fill in. All the block tag does is tell the template engine that a child template may override those portions of the template.

What does {% %} do in Django?

{% extends variable %} uses the value of variable . If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.


2 Answers

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.

like image 50
mpen Avatar answered Sep 28 '22 07:09

mpen


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

like image 42
Camilo Díaz Repka Avatar answered Sep 28 '22 07:09

Camilo Díaz Repka