Language Switcher for Craft 3
A quick and easy language switcher to use with Craft CMS version 3.
I'm working on a new site which needs to have English and French versions. Of course this means a language switcher is needed. For Craft 2 sites I used this solution on Stack Exchange. However due to changes in Craft 3 this no longer works.
A little tweaking and it now works.
{% set currentLanguage = currentSite.language %}
{# Decide which languages should be omitted from language links #}
{% set languageExceptions = currentSite.language %}
{% set otherLocales = craft.app.sites.getAllSites()|without(currentSite.id) %}
{% for site in otherLocales %}
{% if site.id != currentSite.id %}
{% if entry is defined %}
{% set localeEntry = craft.entries.id(entry.id).siteId(site.id).one() %}
{% endif %}
{% if localeEntry.siteId is defined and localeEntry.siteId != currentSite.id %}
{# If entry is localized in other language go there #}
<li>
<a href="{{ localeEntry.url }}">{{ localeEntry.site.name }}</a>
</li>
{% else %}
{# if not localized go to homepage #}
<a href="/">{{ localeEntry.site.name }}</a>
{% endif %}
{% endif %}
{% endfor %}
The above code hides the current language from the switcher. If however you want to have the current language viewable at all times use this.
{% set currentLanguage = currentSite.language %}
{% set otherLocales = craft.app.sites.getAllSites() %}
{% for site in otherLocales %}
{% if entry is defined %}
{% set localeEntry = craft.entries.id(entry.id).siteId(site.id).one() %}
{% endif %}
{% if localeEntry.siteId is defined and localeEntry.siteId != currentSite.id %}
{# If entry is localized in other language go there #}
<li>
<a href="{{ localeEntry.url }}">{{ localeEntry.site.name }}</a>
</li>
{% else %}
{# if not localized go to homepage #}
<a href="/">{{ localeEntry.site.name }}</a>
{% endif %}
{% endfor %}