Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you declare multiple with variables in a django template?

Tags:

python

django

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

like image 880
John Smith Avatar asked May 11 '17 18:05

John Smith


People also ask

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.

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.

How do you do multiple assignments with multiple variables?

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.


1 Answers

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

like image 188
Moses Koledoye Avatar answered Sep 24 '22 15:09

Moses Koledoye