Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django slice numbers in template

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}}
like image 447
9-bits Avatar asked Jan 11 '12 23:01

9-bits


People also ask

How do I slice a list in Django template?

Definition and UsageThe 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.

What is Autoescape in Django?

autoescape. Controls the current auto-escaping behavior. This tag takes either on or off as an argument and that determines whether auto-escaping is in effect inside the block. The block is closed with an endautoescape ending tag.

What is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.

What does the built in Django template tag Lorem do?

lorem tag displays random “lorem ipsum” Latin text. This is useful for providing sample data in templates.


1 Answers

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!

like image 187
Stefano Avatar answered Sep 20 '22 05:09

Stefano