Django: Assigning variables in template

DjangoDjango Templates

Django Problem Overview


How can I assign a variable inside the django templating system ?

Assuming Restaurant is a Model:

{% restaurant_id as restaurant.id %} or {{ restaurant_id as restaurant.id }} are not working.

Django Solutions


Solution 1 - Django

You could use the with template tag, and assign an internal template variable like this:

{% with restaurant_id=restaurant.id %}
... use restaurant_id in this template section ...
{% endwith %}

Solution 2 - Django

Note: You can use filters within the "with" template tag:

foo is {{ foo }}
{% with bar=foo|slice'6:9' %}
  bar is {{ bar }}
{% endwith %}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHellnarView Question on Stackoverflow
Solution 1 - DjangoLaundroMatView Answer on Stackoverflow
Solution 2 - Djangouser2883773View Answer on Stackoverflow