Django:如何使用变量访问模板中的数组索引

时间:2021-10-02 00:33:59

I have array, lets say it:

我有阵列,让我们说:

str_types = ("open", "closed", "extend", "cancel")

Also I've some table. Which have int field named "type", contains number from 1 - 4. If field value is 1, It must print "open", if value equals 2, I must print "closed" etc.

我还有一些桌子。其中int字段名为“type”,包含1到4的数字。如果字段值为1,则必须打印“打开”,如果值等于2,则必须打印“关闭”等。

So in template:

所以在模板中:

{% for a in ticket %}
<div>{{ str_types.a.types }}</div>
{% endfor %}

Result is blank. How to access that str_types array's index?

结果为空白。如何访问str_types数组的索引?

1 个解决方案

#1


1  

You can't do it without custom template tag or filter.

没有自定义模板标记或过滤器,您无法执行此操作。

from django import template

register = template.Library()

@register.filter
def get_by_index(l, i):
    return l[i]

And the in the template:

并在模板中:

{% load my_tags %}
{{ str_types|get_by_index:a.types }}

But why you need this? The django way is to set the choices attribute of the types field and the use it in the template as {{ a.get_types_display }}.

但为什么你需要这个呢? django方法是设置types字段的choices属性,并在模板中将其用作{{a.get_types_display}}。

#1


1  

You can't do it without custom template tag or filter.

没有自定义模板标记或过滤器,您无法执行此操作。

from django import template

register = template.Library()

@register.filter
def get_by_index(l, i):
    return l[i]

And the in the template:

并在模板中:

{% load my_tags %}
{{ str_types|get_by_index:a.types }}

But why you need this? The django way is to set the choices attribute of the types field and the use it in the template as {{ a.get_types_display }}.

但为什么你需要这个呢? django方法是设置types字段的choices属性,并在模板中将其用作{{a.get_types_display}}。