Skip to content

Language switcher

Pierre Stoffe edited this page Apr 26, 2024 · 5 revisions

Adding a language switcher to your website becomes way easier with this plugin. As the craft.languageRedirector.getLanguageOptions() function returns the URLs of the currently-visited Element in all the languages defined in the config file, your language switcher could look like this:

{% set allLanguages = craft.languageRedirector.getLanguageOptions() %}

<ul>
    {% for item in allLanguages %}
        <li>
            <a href="{{ item.url }}" hreflang="{{ item.id }}" lang="{{ item.id }}" title="{{ 'Switch to {language}'|translate({
                language: item.name
            }) }}">
                {{ item.nativeName|capitalize }}
            </a>
        </li>
    {% endfor %}
</ul>

Custom routes

Custom routes make it impossible for craft.languageRedirector.getLanguageOptions() to fetch the URL of the page in other languages automatically. Instead, you'll want to manually send the list of URLs per language to craft.languageRedirector.getLanguageOptions().

In your route-based template:

{% set languageSwitcherUrls = {
    en: 'https://google.com',
    fr: 'https://google.fr',
    nl: 'https://google.nl',
} %}

Where you call the language switcher:

{% set allLanguages = craft.languageRedirector.getLanguageOptions(languageSwitcherUrls ?? null) %}