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.
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.
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.
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 %}
Note: You can use filters within the "with" template tag:
foo is {{ foo }} {% with bar=foo|slice'6:9' %} bar is {{ bar }} {% endwith %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With