views:

284

answers:

3

Pretty simple. I have a Python list that I am passing to a Django template.

I can specifically access the first item in this list using

{{ thelist|first }}

However, I also want to access a property of that item... ideally you'd think it would look like this:

{{ thelist|first.propertyName }}

But alas, it does not.

Is there any template solution to this, or am I just going to find myself passing an extra template variable...

+7  A: 

You can access any item in a list via its index number. In a template this works the same as any other property lookup:

{{ thelist.0.propertyName }}
Daniel Roseman
A: 

Nope. The expression syntax provided by django is pretty limited. You can have a variable reference where you can do thelist.propertyName, and then you can apply filters to the result. You can implement your own filter though which will do what you need something to the effect of

thelist|first|property:"propertyname"

Or may be somebody already implemented such a filter. But staying within the limits of the standard django the only option is extra parameter in the context

mfeingold
+1  A: 

You can combine the with template tag with the first template filter to access the property.

{% with thelist|first as first_object %}
    {{ first_object.propertyname }}
{% endwith %}
Mark Lavin