Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
{# v2 #}
{# http://craftsnippets.com/articles/universal-language-switcher-for-craft-cms #}
{# logic #}
{% set currentElement = craft.app.urlManager.matchedElement %}
{% set sites = craft.app.getSites().getGroupById(currentSite.groupId).getSites() %}
{% set switcherLinks = [] %}
{% for site in sites if site.baseUrl is not empty %}
{% set title = craft.app.i18n.getLocaleById(site.language).nativeName %}
{% set url = site.getBaseUrl() %}
{% if currentElement %}
{% set otherLocaleElement = craft.app.getElements().getElementById(currentElement.id, currentElement.className(), site.id) %}
{% if otherLocaleElement and otherLocaleElement.enabledForSite %}
{% set url = otherLocaleElement.url %}
{% endif %}
{% endif %}
{% set switcherLinks = switcherLinks|merge([{
url: url,
title: title,
countryCode: site.language|split('-')|last,
current: site.id == currentSite.id ? true : false,
language: site.language,
}]) %}
{% endfor %}
{# outputting html #}
{% if switcherLinks|length > 1 %}
<nav aria-label="{{'Switch language'|t}}" aria-role="navigation">
<ul>
{% for switcherLink in switcherLinks %}
<li class="{{switcherLink.current ? 'is-active'}}">
<a href="{{switcherLink.url}}" hreflang="{{switcherLink.language}}" lang="{{switcherLink.language}}">
<span>{{ switcherLink.title }}</span>
<span class="flag-icon flag-icon-{{switcherLink.countryCode}}"></span>
</a>
</li>
{% endfor %}
</ul>
</nav>
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.