1

I'm working on a site that is available in multiple languages and I would like to build a language switcher that will work for both category pages and single entries.

In Craft v2 that was possible but once I switched to Craft v3, I can't find a way to do get the current category page.

For single entries I do the following (simplified):

{% for siteForEntry in entry.getSupportedSites %}       
    {% set site = craft.app.getSites.getSiteById(siteForEntry.siteId) %}        
    {% if site.id == entry.siteId %}
        <li class="language-selection--active-language">
           <a href="#">{{ site.language }} </a> 
        </li>
    {% else %}            
        {% set entryForOtherSite = craft.entries.id(entry.id).site(site).one() %}
            <li class="{% if site.id == entry.siteId %} language-selection--active-language{% endif %} ">
                <a href="{{ entryForOtherSite.getUrl() }}">{{ site.language }} </a>
             </li>
        {% endif %}
 {% endfor %}

Is there a way to do the same thing for categories?

2
  • What about changing every entry to category and running your code again? May 30, 2018 at 19:30
  • It won't work because getSupportedSites returns different things for entries and categories. See my answer below. May 31, 2018 at 9:19

1 Answer 1

1

It turns out that getSupportedSites() returns different results for categories and standard entries so an additional check needs to take place.

The solution below has been tested with a single group with multiple languages, and it works, although I hope there's a better solution than this one:

If the current page is a category then assign it to the entry variable

{% set entry = category %}

Then:

{# Retrieve all supported sites for the current entry #}
{% set supportedSites = entry.getSupportedSites %}

<ul>
{% for siteForEntry in supportedSites %}
  {% if siteForEntry | length == 1 %}
    {# category #}
    {% set site = craft.app.getSites.getSiteById(siteForEntry) %}
    {% set entryForOtherSite = craft.categories.id(entry.id).site(site).one() %}
  {% elseif siteForEntry | length == 2 %}
    {# standard entry #}
    {% set site = craft.app.getSites.getSiteById(siteForEntry.siteId) %}
    {% set entryForOtherSite = craft.entries.id(entry.id).site(site).one() %}
  {% endif %}

  {% if site.id == entry.siteId %}
      {# This is the current language, mark it as active and don't retrieve its url #}
      <li class="current"><a href="#">{{site.language}}</a></li>
  {% else %}
      {# if it's not the current site, get the entry for this site #}
      <li><a href="{{ entryForOtherSite.getUrl() }}">{{site.language}}</a</li>
  {% endif %}

{% endfor %}
</ul>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.