Adds arg to the value. This can be used for adding numbers or concatenating strings.
Variables
age = 30 name = 'Nat'
Template
{{ name|'haniel' }} is {{ age|add:20 }}.
Result
Nathaniel is 50.
Argument: arg
(required)
– an integer or string to add to the value.
Adds arg to the value. This can be used for adding numbers or concatenating strings.
age = 30 name = 'Nat'
{{ name|'haniel' }} is {{ age|add:20 }}.
Nathaniel is 50.
Did we get something wrong? Is there a use case for the
add filter that we should add?
Please let us know.
Commentary
The
addfilter can be used to coerce a string in to an integer in a template. Consider the following:<select name="order"> {% for field in order_fields %} <option value="{{ forloop.counter0 }}" {% if request.GET.order|add:"0" == forloop.counter0 %}selected{% endif %} >{{ field }}</option> {% endfor %} </select>Because
orderis passed on the querystring, it will be a string, butforloop.counter0will be an integer, so the two will never be equal. Coercingrequest.GET.orderto an integer usingaddsolves the problem.An alternative would be to coerce
forloop.counter0in to a string using theslugifyfilter as shown here.