如何在Django模板中显示数组值?

问题描述 投票:0回答:3

我有以下数组,并希望在模板中显示日期名称。

DAYS = ((0, "Saturday"),
        (1, "Sunday"),
        (2, "Monday"),
        (3, "Tuesday"),
        (4, "Wednesday"))

我可以使用{{ DAYS.2.1 }}显示星期一,但我无法使用{{DAYS.class_weekday.key_value.1}}显示。

我从for循环获得class_weekday.key_value但是当我在那里使用class_weekday.key_value时它没有显示任何东西!

谢谢!

python django python-3.x django-rest-framework django-templates
3个回答
3
投票

您可以使用

{{ instance.get_day_display }}

在你的模板中。选择显示值而不是数据库值。

如果要显示所有值:

[ x for x, y in DAYS ]

将返回包含天数列表的列表,


0
投票

按照django

https://docs.djangoproject.com/en/1.10/ref/templates/api/#variables-and-lookups

变量和查找

变量名必须包含任何字母(A-Z),任何数字(0-9),下划线(但它们不能以下划线开头)或点。

点在模板渲染中具有特殊含义。变量名中的点表示查找。具体来说,当模板系统遇到变量名中的点时,它会按以下顺序尝试以下查找:

Dictionary lookup. Example: foo["bar"]
Attribute lookup. Example: foo.bar
List-index lookup. Example: foo[bar]

请注意,模板表达式(如{{foo.bar}}中的“bar”将被解释为文字字符串,而不使用变量“bar”的值(如果模板上下文中存在)。

因此,您可以使用自定义过滤器。

您可以制作自定义模板过滤器:

#here, import DAYS
@register.filter
def return_day(i):
    try:
        return DAYS[i][1]
    except:
        return N.A

并在模板中

{{ class_weekday.key_value|return_day }}

-1
投票

你想要的是DAYS[2][1] :)

© www.soinside.com 2019 - 2024. All rights reserved.