Creating Own Variables inside a Django Template

For all those who have used the Django Framework to make anything, you’re probably familiar with the rules that come along with it. One of the most important things to remember when using Django is that too many calculations aren’t allowed in the Template.

The developers have this enforced on purpose. They feel that all the calculation should be done at the backend through the views and only the required data that has to be shown should be sent to the template. This might not be a bad thing, but it’s not necessarily a good thing always either. Yes few things like filters are allowed… But then, a variable is a variable, right? 🙂

Sometimes it may be necessary to store a certain value in a variable for later use or as per your needs. It isn’t that straightforward in Django. Lots of implementations have come and gone over the past few years which might confuse someone. The simplest, correct and presently working (and only) way to do it is as below:

{% for item in list %}
{% with forloop.counter0 as n %}
<!-- Write HTML and use 'n' wherever required -->
{% endwith %}
{% endfor %}

Like for every python construct, the starting of a block must have an ending. Similarly, once the variable has been created using the “with” statement, a compulsory “endwith” statement must be present once the variable is of no longer use. The same has to be repeated for every variable used in the template. Another important thing to note is that the scope of the variable is limited to the block between the ‘with’ and ‘endwith’ statements.

It really is that simple.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at

Up ↑

%d bloggers like this: