This is because you loop through all but the current locales. Remove the without
filter to loop them all.
{# Loop through all of the site locales, except the current one #}
{% set otherLocales = craft.i18n.getSiteLocaleIds()|without(craft.locale) %}
.
Add "current" class:
To assign the current locale's link a class of "current", compare the looped locale to the current locale, set a variable that you can later test for. Use the ternary operator for short output syntax.
.
Example Code:
With my example code below you first create an array of all the locales you want the language switch to include, and then loop through it. With this technique you can define the order of the output manually or exclude locales from the loop.
{# Configure and loop through selected site locales #}
{% set locales = { 'en': 'English', 'hu': 'Hungarian' } %}
{% for localeId, localeName in locales %}
{# Check if localeId equals the requested page locale #}
{% if localeId == craft.locale %}
{% set current = true %}
{% endif %}
{# 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(localeId).first() %}
{# Make sure that the entry's actually localized to this locale #}
{% if localeEntry.locale == localeId %}
{# Output a link to it #}
<a href="{{ localeEntry.getUrl() }}" class="nav-link{{ current ? ' current' }}">{{ localeName }}</a>
{% else %}
{# Output a link to the hompage #}
<a href="{{ craft.config.siteUrl[localeId] }}" class="nav-link{{ current ? ' current' }}">{{ localeName }}</a>
{% endif %}
{# Not an entry page #}
{% else %}
{# Output the same path with the locale's base URL (`siteUrl`) #}
<a href="{{ craft.config.siteUrl[localeId] ~ craft.request.getPath() }}" class="nav-link{{ current ? ' current' }}">{{ localeName }}</a>
{% endif %}
{% endfor %}
.
Notes:
- The easiest (and recommended) way to use this language switch is to exclusively use entry pages (channel entries, structure entries, or singles) on your site.
- All non entry pages have to have the same URL path / slug for every locale (eg.
http://craft.dev/de/meineindexseite/
andhttp://craft.dev/en/meineindexseite/
). - If you only use entry pages or if you are using localized template folders you should be save to remove the
entry is defined
conditional (incl. the else part) altogether. craft.config.siteUrl[localeId]
only works if siteUrl is configured to take care of localized URLs