CMS Development

TTimes
Contributor

Question about custom language switcher

Following the inputs from @Anton in this thread:

 

https://community.hubspot.com/t5/CMS-Development/Adding-the-language-switcher-in-the-navigation-menu...

I started building my own custom language switcher. 

I currently have a homepage with 'en' as primary and 'da' (danish) translated. I enabled the slug prefix under settings for the english primary and disabled "Enable Language Specific Redirects".

 

 

 

{% set currLang = content.language.languageTag %}
   {{ currLang|pprint }}
   {# here you set all the display names and language tags - you can modify, add/remove as you need - they have to be exactly! like en, en-gb, en-us...#} 
{% set codes = {'English': 'en', 'Dansk': 'da'} %}  

 

 

 


And then the loop:

 

 

 

{% for key, val in codes.items() %}                            
   {% set URL = "/"~content.translated_content[val].slug || val %}
      {{val|pprint}}
      {{content.translated_content[val].slug || val|pprint}}                                
      <li>
         <a class="lang-option" href="{% if URL == '/' %}/{{ content.slug }} {% else %} {{ URL }} {% endif %} "><img class="lang-flag" src="FILE-URL-IN-THE-FILE-MANAGER/assets/flags/{{ val }}.svg" loading="lazy">{{ key }}</a>
      </li>
{% endfor %}

 

 

 

 
However, as you might notice, I experienced that when i was on the english version the URL would return only "/" for the english link but "/da" for the danish version and vice versa. This was the case even when {{ val|pprint }} would actually return both "en" and "da" regardless of what pages i was on.

So i had to check if URL was only "/" and then output content.slug instead, to make both links in the language selector work regardless of what language i was currently viewing the page in.

 

 

 

 

href="{% if URL == '/' %}/{{ content.slug }} {% else %} {{ URL }} {% endif %}

 

 

 

 

But why is this necessary? Why is e.g. the danish language URL var returning only "/" when {{ val }} indeed does contain "da", on the danish version of the page?

I hope my question is somewhat clear. 


0 Upvotes
1 Reply 1
dennisedson
HubSpot Product Team
HubSpot Product Team

Question about custom language switcher

Throwing a couple other people who might have thoughts on this in here.

@Gonzalo , @albertsg -- anything you would want to add?