Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Templating: how to access properties of the first item in a list

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...

like image 308
M. Ryan Avatar asked Sep 25 '09 19:09

M. Ryan


People also ask

What does {{ this }} mean in Django?

What does {{ name }} this mean in Django Templates? Django. It will be displayed as name in HTML. The name will be replaced with values of Python variable. {{ name }} will be the output.

What built in Django template filter capitalizes the first character of the value?

Use {{ obj | capfirst }} to make uppercase the first character only. Using {{ obj | title }} makes it Camel Case.

What is template inheritance in Django?

Template inheritance. The most powerful – and thus the most complex – part of Django's template engine is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override.

What does include does in Django template?

include tag loads a template and renders it with the current context. This is a way of “including” other templates within a template. The template name can either be a variable or a hard-coded (quoted) string, in either single or double quotes.


2 Answers

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 }} 
like image 92
Daniel Roseman Avatar answered Sep 30 '22 09:09

Daniel Roseman


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 %} 
like image 26
Mark Lavin Avatar answered Sep 30 '22 08:09

Mark Lavin