我有阵列,让我们说:
str_types = ("open", "closed", "extend", "cancel")
我还有一些桌子。其中int字段名为" type",包含1到4的数字。如果字段值为1,则必须打印"打开",如果值等于2,我必须打印&#34 ;关闭"等
所以在模板中:
{% for a in ticket %}
<div>{{ str_types.a.types }}</div>
{% endfor %}
结果为空白。如何访问str_types数组的索引?
答案 0 :(得分:1)
如果没有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 }}
用于模板。