---
title: '{% with %}'
description: caches a variable for reuse.
date: '2026-08-02'
categories:
  - Template Tag
  - Logic
canonical: https://coolify.djangotemplatetagsandfilters.com/tags/with/
doc_link: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/#with
---

# {% with %}

caches a variable for reuse.

## 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:

```django
{{ 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:

```django
{% 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:**

```django
{% 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:

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