[Django]-Assign multiple variables in a with statement after returning multiple values from a templatetag

2👍

I don’t think it’s possible without a custom templatetag.

However if your method returns always the same length you can do it more compact like this:

{% with a=var.0 b=var.1 c=var.2 %}
  ...
{% endwith %}

2👍

I’m not sure that this as allowed, however from docs multiple assign is allowed.

But you can assign these 3 variables to 1 variable, which will make it tuple object, which you can easily iterate by its index.

{% with var=object|get_abc %}
  {{ var.0 }}
  {{ var.1 }}
  {{ var.2 }}
{% endwith %}

0👍

Its not supported and its not a flaw of Django Template Language that it doesn’t do that, its Philosophy as stated in the docs:

Django template system is not simply Python embedded into HTML. This
is by design: the template system is meant to express presentation,
not program logic

What you could do is prepare your data on Python side and return appropriate format which will be easy to access in template, so you could return a dictionary instead and use dotted notation with key name:

{# assuming get_abc returns a dict #}
{% with var=object|get_abc %}
  {{ var.key_a }}
  {{ var.key_b }}
  {{ var.key_c }}
{% endwith %}

Leave a comment