Joel Azevedo
Joel Azevedo

Reputation: 616

Add whitespace to string every 3 characters in Jinja2

I have a source of youtube viewcounts, and I want to represent them separated every 3 characters.

Examples: My source is 1897584, I want it to be: 1 897 584; 1200, I want it to be: 1 200... 234989, 234 989... 123, 123... and so on...

Is it possible to split the string every 3 characters using only jinja2?

Cheers in advance.

Upvotes: 2

Views: 1878

Answers (1)

doru
doru

Reputation: 9110

It's doable. You have to make a custom filter - a python function - in your python file. This would do the job:

def number_format(nr):
    list_nr = [i for i in reversed(nr)]
    list_nr_three = ["".join(list_nr[i:i+3]) for i in range(0, len(list_nr), 3)]
    str_nr = " ".join(list_nr_three)
    return str_nr[::-1]

And then add your custom filter to your jinja environment:

environment.filters['number_format'] = number_format

And you can use it in your template file like so:

{{ '1897584'|number_format }}

Upvotes: 2

Related Questions