Django: How to get language code in template?

后端 未结 3 1181
你的背包
你的背包 2021-02-01 01:49

Is there\'s some global variable for gettin\' language code in django template or atleast passing it through view? something like: {{ LANG }} should produce \"en\"

3条回答
  •  终归单人心
    2021-02-01 01:55

    Tested with Django==1.11.2.

    Enable I18N and employ i18n template context processor.

    # setings.py
    
    USE_I18N = True
    # ...
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    # ...
                    'django.template.context_processors.i18n',
                    # ...
                ],
            },
        },
    ]
    

    And then it's simple in the template.

    # template.html
    
    {% load i18n %}
    {{ LANGUAGE_CODE }}
    


    But use render(), not render_to_response(), in your view function so the LANGUAGE_CODE variable is accessible in the template:

    render_to_response()

    This function preceded the introduction of render() and works similarly except that it doesn’t make the request available in the response. It’s not recommended and is likely to be deprecated in the future.

提交回复
热议问题