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
The slice filter returns the specified items from a list. You can define the from (inlcuded) and to (not included) indexes. If you use negative indexes, it means slicing from the end of the list, -1 refers to the last item, -2 refers to the second last item etc.
Django Template Engine provides filters which are used to transform the values of variables;es and tag arguments. We have already discussed major Django Template Tags. Tags can't modify value of a variable whereas filters can be used for incrementing value of a variable or modifying it to one's own need.
Python slice() FunctionThe slice() function returns a slice object. A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.
A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.
you can just use
{{ mylist|slice:"3:8" }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With