Skip to content

Instantly share code, notes, and snippets.

@ademers
Last active October 17, 2017 11:49
Show Gist options
  • Save ademers/7b2604730bd1b205cb23 to your computer and use it in GitHub Desktop.
Save ademers/7b2604730bd1b205cb23 to your computer and use it in GitHub Desktop.
Craft CMS: Language Toggle
{# Language switcher #}
{# Loop through all of the site locales, except the current one #}
{% set otherLocales = craft.i18n.getSiteLocaleIds()|without(craft.locale) %}
{% for locale in otherLocales %}
{# Is this an entry page? #}
{% if entry is defined %}
{# Find the current entry in the other locale #}
{% set localeEntry = craft.entries.id(entry.id).locale(locale).first %}
{# Make sure that it's actually localized to this locale #}
{% if localeEntry.locale == locale %}
{# Output a link to it #}
<li>
<a href="{{ craft.config.siteUrl[locale] ~ (localeEntry.uri != '__home__' ? localeEntry.uri) }}">
{% if craft.locale == "en_ca" %}
Français
{% elseif craft.locale == "fr_ca" %}
English
{% endif %}
</a>
</li>
{% endif %}
{% else %}
{# Just output the same path with the locale's base URL #}
<li>
<a href="{{ craft.config.siteUrl[locale] ~ craft.request.getPath() }}">
{% if craft.locale == "en_ca" %}
Français
{% elseif craft.locale == "fr_ca" %}
English
{% endif %}
</a>
</li>
{% endif %}
{% endfor %}
{# /Language switcher #}
@brandonkelly
Copy link

Change this line:

<a href="{{ craft.config.siteUrl[locale] ~ craft.request.getPath() }}">

to:

{% set path = craft.request.getPath() %}
{% if path %}
    {# Add a trailing slash to it #}
    {% set path = path ~ '/' %}
{% endif %}
<a href="{{ craft.config.siteUrl[locale] ~ path }}">

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment