Django: How to get language code in template?

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" for example.. I really not comfortable when people using request.LANGUAGE_CODE.

Detailed explanation would be appreciated =)


Solution 1:

It's an old topic. But some might find it useful.

{% load i18n %}
...
{% get_current_language as LANGUAGE_CODE %}

Django reference and example.

Solution 2:

If it didn't already exist, you would need to write a template context processor. Here's how you'd do that.

Put this somewhere:

def lang_context_processor(request):
    return {'LANG': request.LANGUAGE_CODE}

And then, add a reference to it the TEMPLATE_CONTEXT_PROCESSORS setting. Something like this:

from django.conf import global_settings

TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
    'myproject.myapp.templatecontext.lang_context_processor',
)

(I recommend adding to the global setting because it means you don't break things accidentally when a new context processor is added to the defaults.)

However, it does exist, as the inbuilt template context processor django.template.context_processors.i18n. You can access it as LANGUAGE_CODE.

Purely for interest, here's the definition of that function:

def i18n(request):
    from django.utils import translation
    return {
        'LANGUAGES': settings.LANGUAGES,
        'LANGUAGE_CODE': translation.get_language(),
        'LANGUAGE_BIDI': translation.get_language_bidi(),
    }

Make sure that you're using a RequestContext for your template rendering, not a plain Context, or it won't work.

Solution 3:

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.