Krystian Cybulski
Krystian Cybulski

Reputation: 11118

Django template alternative to the `with` tag

In Django templates, it is possible to introduce a new named variable to the context using the with tag:

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

I find myself often using it to rename variables so that I can include re-usable templates:

{% with user_list=request.user.friends %}
    {% include '_user_list.html' %}
{% endwith %}

Is there a way to introduce a new variable in the context without using the with tag? I am imagining a tag like set where you call it once like {% set user_list=request.user.friends %} and then do not need to close it off with a {% endset %} tag. This is something akin to the {% trans "This is the title" as the_title %} in function.

If there is not a way to do this, what are some reasons why this is not a good / pythonic / django-way of doing things?

Upvotes: 1

Views: 678

Answers (1)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53999

If you look at the include template tag, you'll see that you can assign and pass variables to the template within the tag itself:

You can pass additional context to the template using keyword arguments:

{% include "name_snippet.html" with person="Jane" greeting="Hello" %}

Upvotes: 3

Related Questions