Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Assigning variables in template

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.

like image 938
Hellnar Avatar asked Dec 15 '11 09:12

Hellnar


People also ask

How do I declare a variable inside a Django template?

Another approach to declare variables in the template is by using custom template tags. Create a custom template tag files named as custom_template_tags.py . Paste the below code in it. Now inside the HTML template use this custom template tag setvar to define a new variable.

Can we create a variable in Django template?

There are tricks like the one described by John; however, Django's template language by design does not support setting a variable (see the "Philosophy" box in Django documentation for templates). Because of this, the recommended way to change any variable is via touching the Python code.


2 Answers

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 %} 
like image 96
LaundroMat Avatar answered Sep 21 '22 23:09

LaundroMat


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

foo is {{ foo }} {% with bar=foo|slice'6:9' %}   bar is {{ bar }} {% endwith %} 
like image 23
user2883773 Avatar answered Sep 21 '22 23:09

user2883773