Paul D. Waite
Paul D. Waite

Reputation: 98816

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, like 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?

Upvotes: 7

Views: 7271

Answers (3)

Paul D. Waite
Paul D. Waite

Reputation: 98816

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.

Upvotes: 4

Manoj Govindan
Manoj Govindan

Reputation: 74705

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

Upvotes: 9

Bernhard Vallant
Bernhard Vallant

Reputation: 50786

You can use the with-templatetag:

{% with browsers|first as first_browser %}
    {{ first_browser.classified_name }}
{% endwith %}

Upvotes: 12

Related Questions