Skip to content

Instantly share code, notes, and snippets.

@ockam
Forked from ademers/craft-cms-language-toggle.html
Last active February 17, 2016 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ockam/0c778b2a43df6f8e88e7 to your computer and use it in GitHub Desktop.
Save ockam/0c778b2a43df6f8e88e7 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>
{% set path = craft.request.getPath() %}
{% if path %}
{# Add a trailing slash to it #}
{% set path = path ~ '/' %}
{% endif %}
<a href="{{ craft.config.siteUrl[locale] ~ path }}">
{% if craft.locale == "en_ca" %}
Français
{% elseif craft.locale == "fr_ca" %}
English
{% endif %}
</a>
</li>
{% endif %}
{% endfor %}
{# /Language switcher #}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment