7

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 Answers 3

12

You can use the with-templatetag:

{% with browsers|first as first_browser %}
    {{ first_browser.classified_name }}
{% endwith %}
Sign up to request clarification or add additional context in comments.

Comments

9

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

1 Comment

I prefer this, because browsers.0.classified_name can also be done
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.