美文网首页
国际化与本地化

国际化与本地化

作者: Tsukinousag | 来源:发表于2023-01-06 21:18 被阅读0次

    1. 在python代码中嵌入

    报错CommandError: Can‘t find msgfmt. Make sure you have GNU gettext tools 0.15 or newer installed._sunshine

    //settings.py
    LANGUAGES = (
    ('zh-hans', gettext_lazy('Simplified Chinese')),
    )
    

    然后注意了要在locale的文件夹下执行命令行

    django-admin makemessages -l zh_Hans
    

    然后编译一下

    django-admin compilemessages
    

    编写views.py以及配置settings.py

    from django.shortcuts import render
    from django.http import HttpResponse
    
    from django.utils.translation import gettext_lazy as _
    
    # Create your views here.
    
    def index(request):
        tmp=_("Hello world!")
        return HttpResponse(tmp)
    
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.locale.LocaleMiddleware",
    
    LANGUAGES = (
        ('zh-hans', gettext_lazy('Simplified Chinese')),
        ('en-us',gettext_lazy('English')),
    )
    
    python manage.py migrate
    python manage.py runserver
    

    2. 在模板中嵌入

    首先编写html文件

    <!DOCTYPE html>
    <html lang="en">
    <head>
        {% load i18n %}
        <meta charset="UTF-8">
        <title>Test</title>
    </head>
    <body>
        <p>{% blocktrans %} {{ person }} say hello {% endblocktrans %}</p>
    </body>
    </html>
    

    同上建立locale文件夹,在app文件夹下

    然后在locale文件夹下修改这个文件

    然后编译一下

    django-admin compilemessages
    

    然后编写views.py把模板导入

    from django.shortcuts import render
    from django.http import HttpResponse
    from django.template import loader
    
    from django.utils.translation import gettext_lazy as _
    
    # Create your views here.
    
    def index(request):
        tmp=_("Hello world!")
        return HttpResponse(tmp)
    
    def test(request):
        t=loader.get_template('test.html')
        return HttpResponse(t.render({
            'person':'tony'
        }))
    

    最后编写一下urls.py就可以了,实验结果如下:

    相关文章

      网友评论

          本文标题:国际化与本地化

          本文链接:https://www.haomeiwen.com/subject/bhkdcdtx.html