We can set the value of a variable in the Django template using with
tag.
{% with name="pythoncircle" %}
<div>Hello {{name}}!</div>
{% endwith %}
This will output the below content.
Hello pythoncircle
One downside of this approach is that we have to write the lines where we are accessing the variable inside with
and endwith
block.
Using with
is useful when using a costly variable multiple times. For example, you are printing the count of rows in a database table then it would be better to set the value of row count in a variable instead of getting it every time from the database.
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
We can rewrite the above with
tag as below as well.
{% with business.employees.count as total %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
We can set multiple variables in one go as below.
{% with var1="hello" var2="pythoncirlce" %}
{{ var1 }} {{var2}}
{% endwith %}
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.
from django import template
register = template.Library()
@register.simple_tag
def setvar(val=None):
return val
Now inside the HTML template use this custom template tag setvar
to define a new variable.
{% load custom_template_tags %}
{% if is_login %}
{% setvar "Save" as action %}
{% else %}
{% setvar "Compile" as action %}
{% endif %}
Would you like to {{action}} this code?
Using the custom template tag, we don't have to write everything inside with block.