206

I am getting an array arr passed to my Django template. I want to access individual elements of the array in the array (e.g. arr[0], arr[1]) etc. instead of looping through the whole array.

Is there a way to do that in a Django template?

3
  • 7
    You can access item like this arr.0, arr.1, ... Another solution : write your own template tag arr|array_item: "0" or something like this. Commented Jul 30, 2014 at 18:41
  • 1
    @rphonika Yes, example here: stackoverflow.com/a/29664945/2714931 Commented Apr 16, 2015 at 3:43
  • @rphonika array_item not found and invalid. Commented Apr 24, 2022 at 11:42

4 Answers 4

337

Remember that the dot notation in a Django template is used for four different notations in Python. In a template, foo.bar can mean any of:

foo[bar]       # dictionary lookup
foo.bar        # attribute lookup
foo.bar()      # method call
foo[bar]       # list-index lookup

It tries them in this order until it finds a match. So foo.3 will get you your list index because your object isn't a dict with 3 as a key, doesn't have an attribute named 3, and doesn't have a method named 3.

Sign up to request clarification or add additional context in comments.

4 Comments

Aren't the first and last more likefoo['bar']?
There seems to be no way to access a list item using a variable index :(
Agree with @VickyChijwani: the fourth option above is not valid. Django templates don't seem to do list-index lookups with variables
@hiyume How to overcome that?
195
arr.0
arr.1

etc.

3 Comments

how to print dynamic like ex: arr.variablename
Is there any way to do this without magic numbers? In other words to "name" the .0 .1 .2 etc...? Such as array["first name"], array["last name"] etc..
@cyberjoac in that case use a dict. In the view: d = {'first_name':'foo', 'last_name': 'bar'}. In the template {{ d.first_name }} will work just fine.
39

You can access sequence elements with arr.0, arr.1 and so on. See The Django template system chapter of the django book for more information.

Comments

15

When you render a request to context some information, for example:

return render(request, 'path to template', {'username' :username, 'email' :email})

You can access to it on template, for variables

{% if username %}{{ username }}{% endif %}

for arrays

{% if username %}{{ username.1 }}{% endif %}
{% if username %}{{ username.2 }}{% endif %}

you can also name array objects in views.py and then use it as shown below:

{% if username %}{{ username.first }}{% endif %}

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.