0

I have a list of values in my view where I want to store some classes name and pass them to the template. Here is the list in the view: menu = ['','disabled','','',''] and my code for the template <li class="{{ menu|slice:"1:2"|first }}"></li>.

So far this is the only working code I came with, is there a better way to retrieve the element menu[2] from this list? what is the proper way in django to callback the element[n] of a list within the template?

adilbenseddik
  • 75
  • 1
  • 5
  • 1
    possible duplicate of [How to access array elements in a Django template?](http://stackoverflow.com/questions/1700661/how-to-access-array-elements-in-a-django-template) – dm03514 Nov 11 '14 at 13:47

3 Answers3

0

menu.1 should work

if you know the exact index of your list, it could be cleaner and more explicit to do retrieval in your view.

context['menu_target'] = menu[1]

instead of having a list of empty values and accessing them in your template

dm03514
  • 54,664
  • 18
  • 108
  • 145
  • `menu.1` works very well, thx. I have 5 menu entries where I want to shift between the css classes `active`, `disabled` and `''` (depending on the view). How would you do? – adilbenseddik Nov 11 '14 at 14:34
0

You can just use menu.2 in your template.

Peter
  • 1,658
  • 17
  • 23
0

An alternative is to get the element[n] that you need in your view, and pass it to the template directly.

Generally speaking, It's a better approch to pass to the template the data that you're going to actually use. So why pass a full list to use only one item of it?

David Dahan
  • 10,576
  • 11
  • 64
  • 137