Can I access attributes of the first object in a list in Django templates?
I’ve got a Django template that’s receiving a list of objects in the context variable browsers
.
I want to select the first object in the list, and access one of its attributes, l开发者_如何学JAVAike this:
<a class="{{ browsers|first.classified_name }}" href="">{{ browsers|first }}</a>
However, I get a syntax error related to the attribute selection .classified_name
.
Is there any way I can select an attribute of the first object in the list?
You can use the with-templatetag:
{% with browsers|first as first_browser %}
{{ first_browser.classified_name }}
{% endwith %}
@lazerscience's answer is correct. Another way to achieve this is to use the index directly. For e.g.
{% with browsers.0 as first_browser %}
<a class="{{ first_browser.classified_name }}" href="">{{ first_browser }}</a>
{% endwith %}
Alternatively, if you’re looping through the list using the {% for %}
tag, you can ignore every object apart the first using the forloop.first
variable, e.g.
{% for browser in browsers %}
{% if forloop.first %}
<a class="{{ browser.classified_name }}" href="">{{ browser }}</a>
{% endif %}
{% endfor %}
That’s probably both less clear and less efficient though.
精彩评论