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"?
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.
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.
{% 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.
{% 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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With