202

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?

ndmeiri
  • 4,979
  • 12
  • 37
  • 45
miket
  • 2,539
  • 3
  • 18
  • 6

4 Answers4

332

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.

Braiam
  • 1
  • 11
  • 47
  • 78
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
190
arr.0
arr.1

etc.

Ofri Raviv
  • 24,375
  • 3
  • 55
  • 55
  • 21
    how to print dynamic like ex: arr.variablename – Nandha Kumar Dec 04 '14 at 12:08
  • 1
    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.. – jhagege Dec 19 '14 at 09:16
  • @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. – Ofri Raviv Dec 19 '14 at 10:49
35

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.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
ema
  • 1,320
  • 11
  • 10
13

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 %}
Braiam
  • 1
  • 11
  • 47
  • 78
Omid Reza Heidari
  • 658
  • 12
  • 27