Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add, multiply number variables in a Django template?

The JS snippet I created relies on the forloop.counter variable being available within a {% for key, value in data.items %}..{% endfor %} tag.

Is there a way to use mathematical operators (*, -, +, /) together with the forloop.counter variable?

like image 568
Charlesliam Avatar asked Aug 20 '13 09:08

Charlesliam


People also ask

How do I declare a variable inside a Django template?

Another approach to declare variables in the template is by using custom template tags. Create a custom template tag files named as custom_template_tags.py . Paste the below code in it. Now inside the HTML template use this custom template tag setvar to define a new variable.


1 Answers

It's possible to use django built-in widthratio template tag and add filter:

  • add 5 to forloop.counter {{forloop.counter|add:5}}
  • subtract 5 from forloop.counter {{forloop.counter|add:"-5"}}
  • devide forloop.counter by 5 {% widthratio forloop.counter 5 1 %}
  • multiply forloop.counter by 5 {% widthratio forloop.counter 1 5 %}
like image 138
Sergey Lyapustin Avatar answered Oct 09 '22 19:10

Sergey Lyapustin