Since we are serving content that is available in multiple languages, we should let our users switch the site's language. We are going to add a language selector to our site. The language selector will consist of a list of available languages, which are displayed using links.
Edit the shop/base.html template of the shop application and find the following lines:
<div id="header">
<a href="/" class="logo">{% trans "My shop" %}</a>
</div>
Replace them with the following code:
<div id="header">
<a href="/" class="logo">{% trans "My shop" %}</a>
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
<div class="languages">
<p>{% trans "Language" %}:</p>
<ul class="languages">
{% for language in languages %}
<li>
<a href="/{{ language.code }}/"
{% if language.code == LANGUAGE_CODE %} class="selected"{% endif %}>
{{ language.name_local }}
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
This is how we build our language selector:
- First, we load the internationalization tags using {% load i18n %}
- We use the {% get_current_language %} tag to retrieve the current language
- We get the languages defined in the LANGUAGES setting using the {% get_available_languages %} template tag
- We use the tag {% get_language_info_list %} to provide easy access to the language attributes
- We build an HTML list to display all available languages and we add a selected class attribute to the current active language
We use the template tags provided by i18n, based on the languages available in the settings of your project. Now open http://127.0.0.1:8000/ in your browser and take a look. You should see the language selector in the top right-hand corner of the site as follows:
Users can now easily switch to their preferred language.