Django: Display current locale in a template

19,529

Solution 1

I solved this by including code below in the template

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

and the variable LANGUAGE_CODE has the value you want (see also django docs for an example usage).

Solution 2

You might want to write your own context processor, which would call to_locale and automatically populate the context with the result -- it would just be something like this.

from django.utils.translation import to_locale, get_language
def locale(request):
    return {'LOCALE': to_locale(get_language())}

Solution 3

I thought of implementing my own custom template tag that would simply output to_locale(get_language()) but the answer above is easier to implement so I like it better.

Share:
19,529
urig
Author by

urig

Updated on June 03, 2022

Comments

  • urig
    urig almost 2 years

    I need to embed the current locale in a Django template's output (as part of a URL to be precise). I know that I can access the current language as {{ LANGUAGE_CODE }} if I { load i18n } but is there a similar way to access the current locale?

    I suppose I could use to_locale() in the view logic and put it in the context for the template, but I'm looking for something more generic that might be part of the Django framework itself. Is there such a syntax?