Skip to content

Instantly share code, notes, and snippets.

@davidhellmann
Last active August 1, 2018 21:27
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save davidhellmann/e002dcfdf1394491b95986d72435488c to your computer and use it in GitHub Desktop.
{# @var craft \craft\web\twig\variables\CraftVariable #}
{# @var entry \craft\elements\Entry #}
{#
Language Switcher
------------------------------------------------------------
{% import '_partials/macros/_macro-languageSwitcher.html' as macroLanguageSwitcher %}
{{ macroLanguageSwitcher.languageSwitcher({
sites: ['siteA', 'siteB']
}, entry) }}
#}
{% macro languageSwitcher(opt, entry) %}
{% set defaults = {
cn: 'm-languageSwitcher',
sites: null | default('all')
} %}
{# -- Merge Default with Options -- #}
{% set opt = opt is defined ? defaults|merge(opt) : defaults %}
{% if opt.sites is defined and entry is defined %}
{# -- Get all Handles -- #}
{% set allSiteHandles = [] %}
{% for site in craft.app.sites.getAllSites() %}
{% set allSiteHandles = allSiteHandles|merge([site.handle]) %}
{% endfor %}
{% set sites = opt.sites %}
{% if sites == 'all' %}
{% set sites = allSiteHandles %}
{% endif %}
<nav class="{{ opt.cn }}">
<ul class="{{ opt.cn ~ '__list' }}">
{% for site in sites %}
{% if site in allSiteHandles %}
<li class="{{ opt.cn ~ '__item' }}">
{% set current = false %}
{# Check if site equals the requested page site #}
{% if site == craft.app.sites.currentSite.handle %}
{% set current = true %}
{% endif %}
{% if entry ?? null %}
{% set siteEntry = craft.entries.id(entry.id).site(site).one() %}
{% if siteEntry and (siteEntry.site.handle is defined and siteEntry.site.handle == site) %}
<a href="{{ siteEntry.getUrl() }}"
class="{{ opt.cn ~ '__link' }}{{ current ? ' ' ~ opt.cn ~ '__link--current' }}">
{{ site }}
</a>
{% else %}
<a href="{{ siteUrl }}"
class="{{ opt.cn ~ '__link' }}{{ current ? ' ' ~ opt.cn ~ '__link--current' }}">
{{ site }}
</a>
{% endif %}
{% else %}
<a href="{{ siteUrl ~ craft.app.request.pathInfo }}"
class="{{ opt.cn ~ '__link' }}{{ current ? ' ' ~ opt.cn ~ '__link--current' }}">
{{ site }}
</a>
{% endif %}
</li>
{% endif %}
{% endfor %}
</ul>
</nav>
{% endif %}
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment