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?
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.
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.
{{ 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.
{% 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.
You can use the with-templatetag:
{% with browsers|first as first_browser %}
{{ first_browser.classified_name }}
{% endwith %}
@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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With