Django: display the current language in a template

Ludovico Fischer

23 Jul 2010

It is good practice to use the lang attribute to specify the language of an HTML document

<html lang="en">

Of course, you could hard code the attribute by yourself in the template; but this information is stored by Django in settings.py (as LANGUAGE_CODE): so why not keep it DRY and retrieve it from there?

Unfortunately, there is no default way to access information in settings.py from a template. One solution is to write a custom template tag.

To create a template tag, make a templatetags directory in your app directory. Inside create a file named language_extras.py (or anything else for that matter; the file name has no importance). Template tags are simply functions which are registered with the template system using a django.template.Library instance.

As our template tag is very simple, we can just write a function which returns the value we want to display:

def current_language():
    from django.conf import settings
    return settings.LANGUAGE_CODE

We register it with:

register = template.Library

register.simple_tag(current_language)

Now we can use our tag in any template this way:

{% load language_extras %}

<html lang="{% current_language  %}">