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

Django: How to access array index in template using variable

我有数组,说吧:

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

我也有一些 table。其中有名为 "type" 的 int 字段,包含 1 - 4 的数字。如果字段值为 1,则必须打印 "open",如果值为 2,则必须打印 "closed" 等

因此在模板中:

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

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

没有custom template tag or filter你做不到。

from django import template

register = template.Library()

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

模板中的:

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

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