Content between an open with
tag (e.g., {% with var1=value2 var2=value2… %}
) and close endwith
tag (e.g., {% endwidth %}
) have access to the variables defined in the open with
tag.
The with
tag is useful for reusing the results of an expensive method. Consider the following template:
{{ jokes.count }} joke{{ jokes.count|pluralize }} that match your search.
In the preceding code, jokes.count
has to be evaluated twice. The following code assigns jokes.count
to joke_count
and then uses the result within the block:
{% with joke_count=jokes.count %} { joke_count }} joke{{ joke_count|pluralize }} that match your search. {% endwith %}
Commentary
Django tags cannot span multiple lines.
It might be tempting to write an open
with
tag like this:Bad code:
But Django will not recognize that as a tag and thus will be surprised by the
endwith
tag. You will end up with an error like this one: