Can I access the attributes of the first object in a list in Django templates?

I have a Django template that gets a list of objects in a context variable browsers.

I want to select the first object in the list and access one of its attributes, for example:

<a class="{{ browsers|first.classified_name }}" href="">{{ browsers|first }}</a>

However, I get a syntax error related to attribute selection .classified_name.

Is there any way to select the attribute of the first object in the list?

+3
source share
3 answers

You can use c-templatetag :

{% with browsers|first as first_browser %}
    {{ first_browser.classified_name }}
{% endwith %}
+8
source
Answer to

@lazerscience is correct. Another way to achieve this is to use the index directly. E.g.

{% with browsers.0 as first_browser %}
    <a class="{{ first_browser.classified_name }}" href="">{{ first_browser }}</a>
{% endwith %}
+5

Alternatively, if you iterate over a list using a tag {% for %}, you can ignore each object individually using a variableforloop.first , e.g.

{% for browser in browsers %}
    {% if forloop.first %}
        <a class="{{ browser.classified_name }}" href="">{{ browser }}</a>
    {% endif %}
{% endfor %}

This is probably both less clear and less effective.

+4
source

Source: https://habr.com/ru/post/1767333/


All Articles