Loop Counter in Django View

Make Loop counter in DJango template language, in html templates.

Advert

Most time loops are used to print out information in array, which won't be easy to read if printed without numeric counter. The information may have a unique ID which might not be sequential or represent the exact count of items printed.

It's straight forward task, use a variable initialized to 1 then increment it with each run var++. But django doesn't allow variable deceleration in templates other than using custom tags, which is not recommended. But Django brings in the box an automatically creates a variable called forloop.counter that holds the current iteration index.


{% for variable in variables %} 
  {{ forloop.counter }} : {{ variable.variable_name }} 
{% endfor %}

The forloop.counter starts with 1, this means the first entry will start with 1 and increments till the loop iterates.

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.

Comments

Wow ! you have someting to tell us. That's great! Please keep in mind that comments are moderated, we employ rel="nofollow" for links, avoid using a spammy word or a domain in name field, it might end up as a Spam. Thanks for reading.

Last 5 Articles

All Articles >

  1. 4 Ways to Increase Conversion Rates using Videos

     
  2. Getting the best customer experience analytics solutions

     
  3. How to Remove an App from Django Project

     
  4. Parse Time HH:mm:ss without date in javascript

     
  5. Software Testing

     

News Letter

Subscribe to our email newsletter for useful tips and valuable resources, sent out every new article release.