I wrote a Django application that serves translated content for German users, and English content for everyone else. Currently I use a base template containing:
<!DOCTYPE html>
<html lang="en">
Obviously this sets the wrong lang
in case the content is served as German.
Possibly I could try something like
<html lang="{{ 'de' if request.LANGUAGE_CODE == 'de' else 'en' }}">
but this feels clumsy and hard to maintain in case more languages are added.
What would be a simple way to set <html lang>
to the actual language served?
CodePudding user response:
You can try this
<html lang="{{ request.LANGUAGE_CODE|default:'en' %}">
this will add request.LANGUAGE_CODE
if it available or it will set default value as en
CodePudding user response:
I figured it out.
The get_current_language tag contains the preferred language of the user.
{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
<html lang="{{ LANGUAGE_CODE }}">
To me the documentation did not make it clear immediately that "preferred language" is not the topmost language from the "Accept-Language" HTTP header but always the language from setting.LANGUAGES
that best matches the user's preference.
In my case settings.py
contains:
LANGUAGE_CODE = "en-us"
LANGUAGES = [("de", _("German")), ("en", _("English"))]
If the user however prefers Italien, get_current_language
will still be en
. With the Django application running locally on port 8000, you can try this with for example:
curl -H 'Accept-Language: it' http://127.0.0.1:8000/ | cut -b 1-50
The output is something like:
<!doctypehtml><html lang="en">...
If no preferred language is provided with the request, the result is the same. So there is no need for a |default:'en'
. You can test this with:
curl http://127.0.0.1:8000/ | cut -b 1-50