Format numbers in django templates

前端 未结 13 1158
清歌不尽
清歌不尽 2020-11-29 17:22

I\'m trying to format numbers. Examples:

1     => 1
12    => 12
123   => 123
1234  => 1,234
12345 => 12,345

It strikes as a

13条回答
  •  失恋的感觉
    2020-11-29 18:18

    The humanize solution is fine if your website is in English. For other languages, you need another solution: I recommend using Babel. One solution is to create a custom template tag to display numbers properly. Here's how: just create the following file in your_project/your_app/templatetags/sexify.py:

    # -*- coding: utf-8 -*-
    from django import template
    from django.utils.translation import to_locale, get_language
    from babel.numbers import format_number
    
    register = template.Library()
    
    def sexy_number(context, number, locale = None):
        if locale is None:
            locale = to_locale(get_language())
        return format_number(number, locale = locale)
    
    register.simple_tag(takes_context=True)(sexy_number)
    

    Then you can use this template tag in your templates like this:

    {% load sexy_number from sexify %}
    
    {% sexy_number 1234.56 %}
    
    • For an american user (locale en_US) this displays 1,234.56.
    • For a french user (locale fr_FR), this displays 1 234,56.
    • ...

    Of course you can use variables instead:

    {% sexy_number some_variable %}
    

    Note: the context parameter is currently not used in my example, but I put it there to show that you can easily tweak this template tag to make it use anything that's in the template context.

提交回复
热议问题