Django 模板: 如何访问列表中第一个项的属性

非常简单。我有一个 Python 列表,我传递给一个 Django 模板。

我可以使用

{{ thelist|first }}

然而,我也想访问该项目的属性... 理想情况下,你会认为它看起来像这样:

{{ thelist|first.propertyName }}

但是,唉,事实并非如此。

是否有任何模板解决方案,或者我只是发现自己传递一个额外的模板变量..。

59017 次浏览

You can access any item in a list via its index number. In a template this works the same as any other property lookup:

\{\{ thelist.0.propertyName }}

You can combine the with template tag with the first template filter to access the property.

{% with thelist|first as first_object %}
\{\{ first_object.propertyname }}
{% endwith %}

If you're trying to access a manytomany field, remember to add all, so it will look like object.m2m_field.all.0.item_property

a potentially clearer answer/syntax for accessing a ManyToManyField property in an object list provided to the django template would look like this:

\{\{ object_list.0.m2m_fieldname.all.0.item_property }}