Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 290
Paul D. Waite Avatar asked Sep 30 '10 10:09

Paul D. Waite


People also ask

What property would you use to access the first element of a list?

The first and last elements are accessed using an index and the first value is accessed using index 0 and the last element can be accessed through length property which has one more value than the highest array index.

How do I slice a list in Django template?

The slice filter returns the specified items from a list. You can define the from (inlcuded) and to (not included) indexes. If you use negative indexes, it means slicing from the end of the list, -1 refers to the last item, -2 refers to the second last item etc.

What does {{ this }} mean in Django?

{{ foo }} - this is a placeholder in the template, for the variable foo that is passed to the template from a view. {% %} - when text is surrounded by these delimiters, it means that there is some special function or code running, and the result of that will be placed here.

What does %% include?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.


2 Answers

You can use the with-templatetag:

{% with browsers|first as first_browser %}
    {{ first_browser.classified_name }}
{% endwith %}
like image 192
Bernhard Vallant Avatar answered Oct 27 '22 12:10

Bernhard Vallant


@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 %}
like image 20
Manoj Govindan Avatar answered Oct 27 '22 12:10

Manoj Govindan