Django Template - New Variable Declaration


Question

Let me preface by I am just starting Python so if this is really a simple question ^_^

I have a html file with the following content:

        {%for d in results%}
        <div class="twt">
            <img src="{{ d.profile_image_url }}" width="48px" height="48px" /> <span> {{ d.text }} </span>
            <span class="date">{{ d.created_at }}</span>
        </div>
    {% endfor %}

which works well but I also would like to declare a variable on this page. Let's say for this example, we can it RowNumber which will increment for each d displayed, spitting out the current RowNumber.

I tried doing:

{{ RowNumber = 0}} 
{{ RowNumber ++ }}

But it doesn't seem to allow me to declare RowNumber.

1
13
4/5/2009 5:03:46 PM

Accepted Answer

Check out the documentation on the for loop.

It automatically creates a variable called forloop.counter that holds the current iteration index.

As far as the greater question on how to declare variables, there is no out-of-the-box way of doing this with Django, and it is not considered a missing feature but a feature. If you really wanted to do this it is possible with custom tags but for the most part the philosophy you want to follow is that mostly anything you want to do that would require this should be done in the view and the template should be reserved for very simple logic. For your example of summing up a total, for example, you could use the add filter. Likewise, you can create your own filters just like with tags.

20
4/5/2009 3:47:46 PM

If you want to set any variable inside a Django template, you can use this small template tag I've written.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon