django slice numbers in template

9-bits picture 9-bits · Jan 12, 2012 · Viewed 21.3k times · Source

Is there a way to get multiple digits of a given number within a django template?

For example:

{{ some_num|get_digit:2 }} 

will give you the second right most digit. For 1224531 it would be 3

Is there a way to get the last 3 digits or the first 5 digits? Like python's slicing?

something like:

{{ some_num|get_digits:2,5}}

Answer

Stefano picture Stefano · Jan 12, 2012

There is a the "slice" template tag

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#slice

It uses the same syntax as Python's list slicing.

Example:

{{ some_list|slice:":2" }}

in python this is equivalent to:

some_list[:2]

BTW your 2nd example would be "2:5" not "2,5"

NB. Python slicing works on any 'sequence'. Strings and lists are sequences. Numbers are not!