I know it's not good practice, but is there a way to declare multiple variables in a with statement in a django template.
For example I want to do something like this:
{% with a="a", b="b", c="c" %}
{{a}}
{{b}}
{{c}}
{% endwith %}
Edit My actual use case is this:
{% with a,b,c=object|get_abc %}
{{a}}
{{b}}
{{c}}
{% endwith %}
Edit 2 New Question for first Edit: Assign multiple variables in a with statement after returning multiple values from a templatetag
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.
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.
You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.
The example on the doc page clearly states that you can assign more than one variable, but you wouldn't need those commas:
{% with alpha=1 beta=2 %}
...
{% endwith %}
Reference:
with
template tag
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