用于数字的 Django 模板过滤器

Django template filter for numbers

我需要这样的 Django 模板过滤器:

1 > 01
2 > 02
10 > 10

你明白了吗?我想把号码的长度设为 2 分钟。

stringformat 内置过滤器的完美用例:

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

演示:

>>> 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