pankaj udaas
pankaj udaas

Reputation: 469

Slicing a list in Django template

If I want to get first 5 elements from a list I would do mylist|slice:"5"

but I want a range, let say from 3 to 7. something like mylist[3:8] how would I do that in template

Upvotes: 30

Views: 25090

Answers (2)

sundar nataraj
sundar nataraj

Reputation: 8692

you can just use

{{ mylist|slice:"3:8" }}

Upvotes: 53

Sahil kalra
Sahil kalra

Reputation: 9034

Its simple you will have to pass this in the slice filter then:

{{ mylist|slice:"3:8" }}

This filter takes care of all type of slicing you can perform on a list

e.g. All this would work:

{{ mylist|slice:"3:8" }}

{{ mylist|slice:":2" }}

{{ mylist|slice:"3:" }}

{{ mylist|slice:":" }}

Upvotes: 31

Related Questions