Search code examples
pythondjangodjango-filters

Django template filter for numbers


I need such Django template filter:

1 > 01
2 > 02
10 > 10

Do you understand? I want to make 2 min length of the number.


Solution

  • Perfect use case for stringformat built-in filter:

    {{ value|stringformat:"02d" }}
    

    Demo:

    >>> from django.template import Template, Context, loader
    >>> values = [1, 2, 10, 100]
    >>> c = Context({'values': values})
    >>>
    >>> t = Template("""
    ... {% for value in values %}
    ...     {{ value }}, {{ value|stringformat:"02d" }}
    ... {% endfor %}""")
    >>> print t.render(c)
        1, 01
        2, 02
        10, 10
        100, 100