Django Templating: how to access properties of the first item in a list

房东的猫 提交于 2019-12-29 02:46:08

问题


Pretty simple. I have a Python list that I am passing to a Django template.

I can specifically access the first item in this list using

{{ thelist|first }}

However, I also want to access a property of that item... ideally you'd think it would look like this:

{{ thelist|first.propertyName }}

But alas, it does not.

Is there any template solution to this, or am I just going to find myself passing an extra template variable...


回答1:


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 }}



回答2:


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 %}



回答3:


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



来源:https://stackoverflow.com/questions/1479206/django-templating-how-to-access-properties-of-the-first-item-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!