Harikrishnan.A.S -
Harikrishnan.A.S -

Reputation: 45

How to access list items in django jinja template dynamically using variable indexing

Django jinja template error - TemplateSyntaxError

I was trying to create sample show users page where I am want to show username, password and role of the users. I will be storing role as numbers and later I am trying to get the role name from a list.

I have hard coded this role names to a list roles = ['admin', 'teacher', 'student'] this roles has been passed to html page as context value. Also, I am passing a num variable for accessing the list items(atm its value is also hard coded, I will be changing this in future)

views.py

def index(request):
   roles = ['admin', 'teacher', 'student']
   num=1
   return render(request=request, template_name='show_all.html', context={'roles': roles, 'num': num})

and inside my html page I am trying to access this list using num variable as given below

show_all.html

{{roles[num]}}
but it is throwing an error

TemplateSyntaxError at /show_all
Could not parse the remainder: '[num]' from 'roles[num]'

there are few solutions that saying roles.0 will get you the first result and roles.1 will give next, But I don't want to hard-code the index there.

requirements.txt

asgiref==3.5.2
Django==4.1.3
sqlparse==0.4.3
tzdata==2022.6

I have tried

{{roles.num}}
{{roles.get(num)}}
{{roles[num]}}

nothing is giving me desired result.

Upvotes: 1

Views: 1050

Answers (1)

allexiusw
allexiusw

Reputation: 1743

Best approach:

def roli(roles, i):
    """Return the rol[i]"""
    return roles[i]

In Jinja:

{{ roles|roli:i }}

I would recomend you to read the documentation about tags: https://docs.djangoproject.com/en/4.1/howto/custom-template-tags/ you need some extra steps to register the template tag.

Other approach. A workaround could be the following:

def index(request):
   roles = ['admin', 'teacher', 'student']
   num=1
   return render(request=request, template_name='show_all.html', context={'roles': roles, 'num': num, 'rolesi': roles[num]})

And then: show_all.html

{{rolesi}}

Upvotes: 1

Related Questions