with Tag

Logic Most Useful

Argument(s): name-value pairs

Documentation

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:

{% with
  var1 = 'very long value'
  var2 = 'very long value'
  var3 = 'very long value'
%}

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:

Invalid block tag on line 37: 'endwith'. Did you forget to register or load this tag?

Did we get something wrong? Is there a use case for the with tag that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on Oct. 30, 2022, 1:22 p.m. EST