DEV Community

bhagvan kommadi
bhagvan kommadi

Posted on

Django Template - Tips

Found these helpful :

Iterating dictionary

{% for key, values in data.items %}
<tr>
<td>{{key}}</td>
{% for v in values[0] %}
<td>{{v}}</td>
{% endfor %}
</tr>
{% endfor %}

_Loop counter _

{% for item in item_list %}
{{ forloop.counter }} # index 1 start
{{ forloop.counter0 }} # index 0 start
{% endfor %}

Mathematical operations

`{% load mathfilters %}

Basic math filters

  • 8 + 3 = {{ 8|add:3 }}
  • 13 - 17 = {{ 13|sub:17 }}
  • {% with answer=42 %}
  • 42 * 0.5 = {{ answer|mul:0.5 }}
  • {% endwith %} {% with numerator=12 denominator=3 %}
  • 12 / 3 = {{ numerator|div:denominator }}
  • {% endwith %}
  • |-13| = {{ -13|abs }}

`
String expressions

Skills

{% with form.instance.skills|split:"," as skills %}
{% for skill in skills %}
{{ skill }}<br>
{% endfor %}
{% endwith %}

extracting character
<a href="tel://+1{{ phone|cut:'-' }}">Phone</a>

Top comments (0)