如何访问 Django 模板中的数组元素? [英] How to access array elements in a Django template?

查看:23
本文介绍了如何访问 Django 模板中的数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个数组 arr 传递给我的 Django 模板.我想访问数组中数组的各个元素(例如 arr[0]arr[1])等,而不是遍历整个数组.>

有没有办法在 Django 模板中做到这一点?

解决方案

请记住,Django 模板中的点表示法用于 Python 中的四种不同表示法.在模板中,foo.bar 可以表示以下任何一种:

foo[bar] # 字典查找foo.bar # 属性查找foo.bar() # 方法调用foo[bar] # 列表索引查找

它按此顺序尝试它们,直到找到匹配项.所以 foo.3 会给你你的列表索引,因为你的对象不是一个以 3 作为键的字典,没有名为 3 的属性,也没有名为 3 的方法.

I am getting an array arr passed to my Django template. I want to access individual elements of the array in the array (e.g. arr[0], arr[1]) etc. instead of looping through the whole array.

Is there a way to do that in a Django template?

解决方案

Remember that the dot notation in a Django template is used for four different notations in Python. In a template, foo.bar can mean any of:

foo[bar]       # dictionary lookup
foo.bar        # attribute lookup
foo.bar()      # method call
foo[bar]       # list-index lookup

It tries them in this order until it finds a match. So foo.3 will get you your list index because your object isn't a dict with 3 as a key, doesn't have an attribute named 3, and doesn't have a method named 3.

这篇关于如何访问 Django 模板中的数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆