Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling block inside an if condition: django template

I have been trying to call a block inside an if condition in django template.

I have a base template. I have many other templates that extend the base template. I have defined a block in base template:

{% block test_block %}Test{% endblock %} 

I then want to override this block on a certain condition in the other templates. If the condition fails, the block shouldn't get overridden. This is something what I have written:

{% if test_value %}{% block test_block %}Development{% endblock %}{% endif %} 

This actually (or may be virtually) ignores the if condition.

What I finally did:

{% block test_block %}{% if test_value %}Development{% else %}{{ block.super }}{% endif %}{% endblock %} 

I had to do something like this everywhere it was required.

Is this the best way? Is this the only way? Why can't I try the first way of mine? Or is there any mistake from my side?

like image 957
Sandip Agarwal Avatar asked Aug 23 '12 09:08

Sandip Agarwal


People also ask

What does %% include?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.

What does {% %} mean 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.

What is Forloop counter Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.


1 Answers

You haven't made a mistake - template blocks are included regardless of any conditionals around them. You can see this from this line of the ExtendsNode class of django/template/loader_tags.py in the Django source code:

self.blocks = {n.name: n for n in nodelist.get_nodes_by_type(BlockNode)]} 

When the {% extends %} is being rendered, it fetches all block nodes from the template directly and stores them for rendering when the parent comes across those blocks. Whether those blocks in the child were inside conditionals or not isn't considered.

like image 158
M Somerville Avatar answered Sep 22 '22 18:09

M Somerville