Skip to content Skip to sidebar Skip to footer

Assign Multiple Variables In A With Statement After Returning Multiple Values From A Templatetag

Is there a way to assign multiple variables in a with statement in a django template. I'd like to assign multiple variables in a with statement after returning multiple values from

Solution 1:

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 %}

Solution 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.

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

Solution 3:

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 #}
{% withvar=object|get_abc %}
  {{ var.key_a }}
  {{ var.key_b }}
  {{ var.key_c }}
{% endwith %}

Post a Comment for "Assign Multiple Variables In A With Statement After Returning Multiple Values From A Templatetag"