4

I'm porting across a multilingual project from Craft2 to Craft3 and have to rebuild the language switcher. I was previously using the .nativeName method but apparently this is deprecated. I've got a really basic one working for flipping between the English and French versions of my site :

{% set langSwitcher = craft.app.sites.getAllSites() %}

{% for lang in langSwitcher %}
   {# Get base URL #}
   {% set url = alias(lang.baseUrl) %}
   <a href="{{url}}">{{ lang.language }}</a>
{% endfor %}

The {{ lang.language }} is outputting en & fr but how do I get it to display the full native language names i.e English & Francais?

I found the getDisplayName() function in the docs but can't seem to get it working properly: https://docs.craftcms.com/api/v3/craft-i18n-locale.html#public-methods

1 Answer 1

4

The site.language attribute is just a string, i.e. the language code or locale ID, e.g. 'en'.

To get the native name you'll need to go through the I18N service to pull the actual Locale object via that locale ID:

{% set locale = craft.app.i18n.getLocaleById(lang.language) %}
<a href="{{url}}">{{ locale.nativeName }}</a>

Edit: As @Dr_Codswallop mentions in the comments, locale.nativeName is deprecated in Craft 3, and will be removed completely in Craft 4. locale.displayName should be used instead.

3
  • Thankyou Mats! I'd tried that technique but didn't realise getLocaleByID() accepted a string, I thought anything getxxxById required integers. My mistake. Aug 1, 2018 at 16:14
  • 1
    If it helps anyone else on Craft3, locale.nativeName will work for now but is deprecated. Use locale.displayName instead. Aug 2, 2018 at 0:51
  • You're completely right, @Dr_Codswallop – thanks! And yeah, I agree that the getLocaleById() method name is a bit misleading/unconventional. Usually in Craft, "ID" refers to a unique (integer) ID. You should put in a feature request that they rename the method to getLocaleByCode or something similar :P Aug 2, 2018 at 8:05

Your Answer

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

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