views:

20

answers:

3

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.

+3  A: 

You can use the with-templatetag:

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

@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 %}
Manoj Govindan
A: 

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.

Paul D. Waite