views:

1940

answers:

1

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.

+10  A: 

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.

Paolo Bergantino
Thanks, what if I really needed to have a new variable? for example adding up the totals of certain parameters...
TimLeung
Then you'd have to use a custom tag or filter -- the Django templating language simply doesn't allow you to declare new variables.
mipadi
Django's template language was designed to avoid the "in-template" coding style of PHP, ASP, JSP, etc, so this kind of declaration, as Paolo and mipadi have said, is deliberately missing. The spirit of the templates is that any processing logic, like addition, should be done in the view function.
Jarret Hardie
You could find a {% sum %} tag or build one yourself.
Soviut
+1: Quote the documentation. If you need another variable or some processing, you're supposed to put it in your view function. Not your template. Templates are very skinny presentation.
S.Lott