Assign multiple variables in a with statement after returning multiple values from a templatetag

泪湿孤枕 提交于 2020-01-03 20:46:11

问题


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 a templatetag

My use case is this:

{% with a,b,c=object|get_abc %}
    {{a}}
    {{b}}
    {{c}}
{% endwith %} 

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



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



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


来源:https://stackoverflow.com/questions/43925276/assign-multiple-variables-in-a-with-statement-after-returning-multiple-values-fr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!