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?

1

3 Answers 3

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

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

1 Comment

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?
0

You can just use menu.2 in your template.

1 Comment

TS asks: "is there a better way to retrieve the element menu[2] from this list?"
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?

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.