Jump to content
Gadgetto

Set up a nice language switcher for your website

Recommended Posts

Hello,

I'm very new to ProcessWire but already fell in love with this CMS/CMF! I just finished my first small project and as I saw a lot of questions and different answers in this forum on how to set up a nice language switcher for your website, I decided to write my first tutorial.

----------

Please note:

I rewrote this tutorial since I was made aware and learned that flags should not be used for language selectors!

There are some threads here in the forum (and from external sources) where this question is discussed:

https://processwire.com/talk/topic/13196-adding-image-field-to-language/
http://daily.unitedlanguagegroup.com/stories/editorials/inside-design-language-selector-no-flags
https://processwire.com/talk/topic/16524-extending-languages-template/
http://www.flagsarenotlanguages.com/blog/why-flags-do-not-represent-language/
https://processwire.com/talk/topic/14241-language-names-and-utf8-page-names/

Thanks,

@ottogal

@bernhard

@jmartsch

@kongondo

an all others for your hints!

----------

 

TUTORIAL - Set up a nice language switcher for your website - here we go:

 

language-switcher-demo.gif.1106b612803111f899091fbe3caa39fc.gif

This will be the desired result!

 

Step 1)

Setup at least 2 languages in your PW install. In my case it's German (default language) + English:

 

screenshot-languages-setup.png.ac0446cc50c2350b96db305c2c0b44d9.png

 

Step 2)

Add a custom field

Type = Text
Name = languagecode

This will hold the ISO 639-1 two-letter language code for the respective language. The field is needed to provide a simple method for outputting the language code in your templates. Without this field, you will need to programmatically construct your two-letter language code output via PHP (at least for the default language, as ProcessWire doesn't allow to rename the default language and it will always be called default).

Here is an overview for ISO 639-1 two-letter language codes:

https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes

 

screenshot-languages-field-languagecode.thumb.png.d63ba6a49a151dd4b3bb5d8369aa4f6e.png

 

Step 3)

Add this field to the system template: language.

To achieve this, go to Setup / Templates and activate the filter Show system templates:

 

screenshot-system-templates.png.977e78e800e122a83d108a55315bd620.png

 

Now you can add the previously created field languagecode to the language template.

 

screenshot-system-template-fields.png.1419396e292ff127bca922b47e7ca538.png

 

Step 4)

Edit your languages and fill in the appropriate values.

a) default (German)

Name = default (this can't be changed and is read only)
Title = Deutsch (in both language tabs! - this is important as your visitor should always see his language item ... in his language)
languagecode = de

 

screenshot-languages-german.png.e68bda4ab148d6baf7777112856f00af.png

 

b) english (English)

Name = english
Title = English (in both language tabs! - this is important as your visitor should always see his language item ... in his language)
languagecode = en

 

screenshot-languages-english.png.f72e4f827fdd7b65a741ea770ad6a4f7.png

 

Step 5)

Now we are ready to write our template output!


As we already have the appropriate two-letter ISO language code (languagecode field), we can use this in our html lang property:

 

<html lang="<?php echo $user->language->languagecode; ?>">

 

Also the rel alternate output in the html head is simple. Put the following code within your <head></head> area:

 

<?php

// Handle output of 'hreflang' link tags for multi-language (SEO!)
foreach ($languages as $language) {
    
    if (!$page->viewable($language)) { continue; }
    
    // Get the http URL for this page in the given language
    $url = $page->localHttpUrl($language); 
    
    // Get the language code using custom languagecode field
    $languagecode = $language->languagecode;
    
    echo PHP_EOL.'<link rel="alternate" hreflang="'.$languagecode.'" href="'.$url.'">';
}

?>

 

In my sample I've used Boostrap 4 and the code below shows a complete navbar with our language switcher (BTW the language switcher will always be visible, even when the bootstrap navbar is collapsed):

 

<nav id="mainnav" class="navbar navbar-expand-lg navbar-light px-4 px-md-5 sticky-top">
    <a class="navbar-brand" href="<?php echo $config->urls->root; ?>">
        <img src="<?php echo $config->urls->templates; ?>images/logo-rund-80x80.png" alt="">
        Your Site Title
    </a>
    <ul class="navbar-nav ml-auto mr-3 mr-lg-0 order-lg-last d-none d-xs-custom-flex language-switcher" aria-label="<?php echo __('Sprache wechseln') ?>">
        <?php
        echo '<li class="nav-item dropdown">';

        // Construct the language prompt in the current user language
        $prompt = $user->language->title.' ('.strtoupper($user->language->languagecode).')';

        // Current language = dropdown-toggle
        echo '<a class="nav-link dropdown-toggle" href="#languages" id="language-select" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">';
        echo '<span class="world-icon"></span><span class="sr-only">'._x('(aktuelle Sprache)', 'navigation').': </span> '.$prompt;
        echo '</a>';
        
        echo '<div id="languages" class="dropdown-menu dropdown-menu-right" aria-labelledby="language-select">';

        foreach ($languages as $language) {

            // Get the http URL for current page in the given language
            $url = $page->localHttpUrl($language);
            
            // Construct the language prompt in the given language
            $prompt = $language->title.' ('.strtoupper($language->languagecode).')';
                                                    
            // Next language item (except current language)
            if ($user->language->id != $language->id) {
                if (!$page->viewable($language)) {
                    echo '<span class="dropdown-item disabled">'.$prompt.'</span>';
                } else {
                    echo '<a class="dropdown-item" href="'.$url.'">'.$prompt.'</a>';
                }
            }
        }
        echo '</div>';
        echo '</li>';
        ?>
    </ul>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarMainMenu" aria-controls="navbarMainMenu" aria-expanded="false" aria-label="<?php echo __('Menü einblenden / ausblenden') ?>">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse my-3 my-lg-0" id="navbarMainMenu">
        <ul class="navbar-nav mr-auto">
            <?php
                
    		// Top navigation consists of homepage and its visible children
    		foreach ($homepage->and($homepage->children("template=main-page|news|contact-points")) as $item) {
                
    			if ($item->id == $page->rootParent->id) {
        			echo '<li class="nav-item active">';
        			echo '<a class="nav-link" href="'.$item->url.'">'.$item->title.'<span class="sr-only"> '._x('(aktuelle Seite)', 'navigation').'</span></a>';
        			echo '</li>';
    			} else {
        			echo '<li class="nav-item">';
        			echo '<a class="nav-link" href="'.$item->url.'">'.$item->title.'</a>';
        			echo '</li>';
    			}
            
    		}
    		
            ?>
        </ul>
    </div>
</nav>

 


That's it! I hope you will like my tutorial and if there are any questions, critics or improvements please let me know!

Thanks,
Martin

 

Edited by Gadgetto
Removed the language flags from tutorial as this is bad practise!
  • Like 11
  • Thanks 2

Share this post


Link to post
Share on other sites

Hi Gadgetto,

two remarks:

(1)  Your very first animated GIF shows the wrong flag for Germany: It's the flag of Austria - a German speaking country, that's true.

This is a great example for the following insight:

(2) It is not the right way to distinguish languages by flags!

There are some threads here in the forum where this question is discussed. When I find some link, I'll share it.

  • Like 3

Share this post


Link to post
Share on other sites

Good objections that I had never thought of before! If I only could edit my post I‘d correct the tutorial...

  • Like 2

Share this post


Link to post
Share on other sites

Hi @Gadgetto,

if you don't have edit links in your posts, it may be a limitation for new forum users, that will go away after a number of posts. Not really sure so. 

If I will find out more, I come back here or PM you. 

  • Like 1

Share this post


Link to post
Share on other sites

I have an update ready for this tutorial! As soon as I can edit my posts I will put the changes online!

  • Like 2

Share this post


Link to post
Share on other sites

Thx for the tutorial!

You might re-think the approach of using flags for your language switcher. See http://www.flagsarenotlanguages.com/blog/ and http://www.flagsarenotlanguages.com/blog/why-flags-do-not-represent-language/ for example. Or this one: https://wplang.org/never-use-flags-language-selection/

15 hours ago, ottogal said:

(1)  Your very first animated GIF shows the wrong flag for Germany: It's the flag of Austria - a German speaking country, that's true.

Actually this comment proves the problem with flags... for me the comment sounded weird at first sight (because reading "my" flag as "wrong" felt strange 😉 ), but actually that's exactly the problem with flags and it might be better to have a text-only version.

IMHO adding a language switcher is still too much hazzle... Maybe I'll build a small module for that as I'm building a multilang site right now anyhow. Or are there already solutions?

  • Like 2

Share this post


Link to post
Share on other sites

@Gadgetto I wanted to say the same as @bernhard said, but he was quicker. Flags are no indicator for languages but indicate countries instead. This is something I constantly tell my customers, that want to have multi-language sites. For a good implementation of a language switcher take a look at https://www.p-jentschura.com

There I follow best practices for a language switcher.

  • Like 3

Share this post


Link to post
Share on other sites
16 hours ago, Gadgetto said:

If I only could edit my post I‘d correct the tutorial.

That's strange. At 23 posts you should really be able to edit your posts. A recent upgrade probably messed things up or your account got messed up in some way. Anyway, @horst is looking into it.

Thanks for your enthusiasm for ProcessWire and your willingness to share your experience at this early stage 🙂.

  • Like 2

Share this post


Link to post
Share on other sites

Thanks @kongondo, you are one of the first to say something  positive! Had only critics so far (probably fair) ... 🙂

Already thought that with my basic knowledge it was a bit too early to write a tutorial. It was more a lesson for myself because I searched the forum on how to implement a language switcher for front-end. The clues I found were all a little unclear and incomplete. Especially the hints about getting the correct ISO code using php conditions although we have the wonderful custom fields to our disposal were not exactly satisfying.

  • Like 2

Share this post


Link to post
Share on other sites
22 minutes ago, Gadgetto said:

you are one of the first to say something  positive! Had only critics so far (probably fair)

Martin, sorry if we came across in a not-so-positive way 🙂. Please don't take it personally; I'm pretty certain it is the code that was being critiqued (and given that what you wrote was a tutorial, meaning others could learn from it and apply its principles, it's understandable that suggestions were made on how it could be improved). I promise you, this is a very friendly forum 🙂.

26 minutes ago, Gadgetto said:

Already thought that with my basic knowledge it was a bit too early to write a tutorial. 

Not necessarily, especially if you throw in a disclaimer in there. Many times it is about the journey, not the destination. Whereas you set out to write a tutorial, from where I stand, that in itself is only part of the story. The other part of the story is what you are unconsciously telling newbies. That story says, hey, look guys, I found this new toy and look at what I can already do with it 😉

  • Like 7

Share this post


Link to post
Share on other sites
1 hour ago, Gadgetto said:

Thanks @kongondo, you are one of the first to say something  positive!

7 hours ago, bernhard said:

Thx for the tutorial!

In my head this (and also the hints regarding the flags) was positive 😉 

42 minutes ago, kongondo said:
1 hour ago, Gadgetto said:

Already thought that with my basic knowledge it was a bit too early to write a tutorial. 

Not necessarily, especially if you throw in a disclaimer in there. Many times it is about the journey, not the destination. Whereas you set out to write a tutorial, from where I stand, that in itself is only part of the story. The other part of the story is what you are unconsciously telling newbies. That story says, hey, look guys, I found this new toy and look at what I can already do with it 😉

Agree. That's what I like so much about the community. Throw in an idea and get valuable feedback instantly. There will also be times where you share something and get the hint that what you've done is already available in some way. At least that happened to me several times.

Nothing about that is negative. It's just holding up the quality of the forum and clarifying why your approach might be different and better for special situations.

 

I'd highly encourage you to continue writing tutorials. It will help you a lot and likely it will also help others. And nobody (here) knows everything. Except Ryan, of course 😉😄

  • Like 4

Share this post


Link to post
Share on other sites
12 hours ago, bernhard said:

Actually this comment proves the problem with flags... for me the comment sounded weird at first sight (because reading "my" flag as "wrong" felt strange 😉 ), but actually that's exactly the problem with flags and it might be better to have a text-only version.

@bernhard  You're right, my comment really sounds a bit weird, and I apologize for that. (I became aware of that soon after having posted.)

Of course, if someone uses a flag to indicate the German language, it's not "wrong" to take the Austrian one and not the German one - both are equally suitable for this purpose, or unsuitable. Just because of a possible ambiguity of this kind they both are unsuitable - that's the point of my remark.

I also apologize to @Gadgetto: My intention was not to criticize, but to give some well-meant advice.

  • Like 2

Share this post


Link to post
Share on other sites

Hey,

no one has to apologize for their criticism! I am very grateful for it and have learned something new again! Thanks all for your help!

I have revised the tutorial and hope that others can learn something too.

Greetings,
Martin

  • Like 3

Share this post


Link to post
Share on other sites

Thank you @Gadgetto for taking our improvements into account and updating you tutorial.

However, I spotted a small error in your screencast/animation:

If the language is switched to english then the word "german" instead of "Deutsch" appears. As you wrote yourself in your tutorial, the language should be written in the language itself 😉

On 11/25/2018 at 5:38 PM, Gadgetto said:

! - this is important as your visitor should always see his language item ... in his language

I am happy to welcome another happy ProcessWire addict into our community 🙂

  • Like 2

Share this post


Link to post
Share on other sites

@jmartsch you are right! -again ... 🙂

Corrected! This was the wrong attachment version. The forum software doesn't make it easy to exchange screenshots or to choose the right attachment. 

  • Like 2

Share this post


Link to post
Share on other sites
On 11/26/2018 at 10:30 AM, Gadgetto said:

Already thought that with my basic knowledge it was a bit too early to write a tutorial. It was more a lesson for myself

I think it is amazing that you took to writing a tutorial for us this early in your involvement with the community.

Good job amigo 🙂

  • Like 3

Share this post


Link to post
Share on other sites
3 minutes ago, OrganizedFellow said:

I think it is amazing that you took to writing a tutorial for us this early in your involvement with the community.

Good job amigo 🙂

Thank you for your kind words!:-)

  • Like 2

Share this post


Link to post
Share on other sites

A huge thank you to @Gadgetto for this tutorial. This is my first time with multi-language, and Gadgetto provided the perfect tutorial for beginners such as myself to learn from. I worked my way through the tutorial and can attest it works beautifully and I could follow along without getting lost.

I now have a wonderful language switcher on my site AND the html lang tag AND the href lang alternate tags, all thanks to Gadgetto's great tutorial above. The screenshots were really helpful too. His code really should be a must-read for those making their first multi-language site. Thanks again! 😀

  • Like 4

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By FireWire
      Hello community!

      I want to share a new module I've been working on that I think could be a big boost for multi-language ProcessWire sites.

      Some background, I was looking for a way for our company website to be efficiently translated as working with human translators was pretty laborious and a lack of updating content created a divergence between languages. I, and several other devs here, have talked about translation integrations and have recognized the power that DeepL has. DeepL is an AI deep learning powered service that delivers translation quality beyond any automated service available. After access to the API was opened up to the US, I built Fluency, a DeepL translation integration for ProcessWire.
      Fluency brings automated translation to every multi-language field in the admin, and also provides a translation tool allowing the user to translate their text to any language without it being inside a template's field. With Fluency you can:
      Translate any plain textarea or text input Translate any CKEditor content (yes, with markup) Translate page names for fully localized URLs on every page Translate your in-template translation function wrapped strings Translate modules DeepL offers translations to the following languages: English (US), English (UK), German, French, Spanish, Portuguese (EU), Portuguese (Brazil, Italian, Dutch, Polish, Russian, Japanese, Chinese (Simplified)
      Installation and usage is completely plug and play. Whether you're building a new multi-language site, need to update a site to multi-language, or simply want to stop manually translating a site and make any language a one-click deal, it could not be easier to do it. Fluency works by having you match the languages configured in ProcessWIre to DeepL's. You can have your site translating to any or all of the languages DeepL translates to in minutes (quite literally).
      Let's break out the screenshots...
      When the default language tab is shown, a message is displayed to let users know that translation is available. Clicking on each tab shows a link that says "Translate from English". Clicking it shows an animated overlay with the word "Translating..." cycling through each language and a light gradient shift. Have a CKEditor field? All good. Fluency will translated it and use DeepL's ability to translate text within HTML tags. CKEditor fields can be translated as easily and accurately as text/textarea fields.

      Repeaters and AJAX created fields also have translation enabled thanks to a JavaScript MutationObserver that searches for multi-language fields and adds translation as they're inserted into the DOM. If there's a multi-language field on the page, it will have translation added.

      Same goes for image description fields. Multi-language SEO friendly images are good to go.

      Creating a new page from one of your templates? Translate your title, and also translate your page name for native language URLs. (Not available for Russian, Chinese, or Japanese languages due to URL limitations). These can be changed in the "Settings" tab for any page as well so whether you're translating new pages or existing pages, you control the URLs everywhere.

      Language configuration pages are no different. Translate the names of your languages and search for both Site Translation Files (including all of your modules)

      Translate all of the static text in your templates as well. Notice that the placeholders are retained. DeepL is pretty good at recognizing and keeping non-translatable strings like that. If it is changed, it's easy to fix manually.

      Fluency adds a "Translate" item to the CMS header. When clicked this opens up a modal with a full translation tool that lets the user translate any language to any language. No need to leave the admin if you need to translate content from a secondary language back to the default ProcessWire language. There is also a button to get the current API usage statistics. DeepL account owners can set billing limitations via character count to control costs. This may help larger sites or sites being retrofitted keep an eye on their usage. Fluency can be used by users having roles given the fluency-translate permission.

      It couldn't be easier to add Fluency to your new or existing website. Simply add your API key and you're shown what languages are currently available for translation from/to as provided by DeepL. This list and all configuration options are taken live from the API so when DeepL releases new languages you can add them to your site without any work. No module updates, just an easy configuration. Just match the language you configured in ProcessWire to the DeepL language you want it to be associated with and you're done. Fluency also allows you to create a list of words/phrases that will not be translated which can prevent items such as brands and company names from being translated when they shouldn't

       
      Limitations:
      No "translate page" - Translating multiple fields can be done by clicking multiple translation links on multiple fields at once but engineering a "one click page translate" is not feasible from a user experience standpoint. The time it takes to translate one field can be a second or two, but cumulatively that may take much longer (CKEditor fields are slower than plain text fields). There may be a workaround in the future but it isn't currently on the roadmap. No "translate site" - Same thing goes for translating an entire website at once. It would be great, but it would be a very intense process and take a very (very) long time. There may be a workaround in the future but it isn't on the roadmap. No current support for Inline CKEditor fields - Handling for CKEditor on-demand hasn't been implemented yet, this is planned for a future release though and can be done. I just forgot about it because I've never really used that feature personally.. Alpha release - This module is in alpha. Releases should be stable and usable, but there may be edge case issues. Test the module thoroughly and please report any bugs via a Gitlab issue on the repository or respond here. Please note that the browser plugin for Grammarly conflicts with Fluency (as it does with many web applications). To address this issue it is recommended that you disable Grammarly when using Fluency, or open the admin to edit pages in a private window where Grammarly may not be loaded. This is an issue that may not have a resolution as creating a workaround may not be possible. If you have insight as to how this may be solved please visit the Gitlab page and file a bugfix ticket.
      Requirements:
      ProcessWire  3.0+ UIKit Admin Theme That's Fluency in a nutshell. A core effort in this module is to create it so that there is nothing DeepL related hard-coded in that would require updating it when DeepL offers new languages. I would like this to be a future-friendly module that doesn't require developer work to keep it up-to-date.
      It's Free
      This is my first real module and I want to give it back to the community as thanks. This is the best CMS I've worked with (thank you Ryan & contributors) and a great community (thank you dear reader). The only cost to use this is a subscription fee for the DeepL Pro API. Find out more and sign up here.
      Download & Feedback
      Download the latest version here
      https://github.com/SkyLundy/Fluency-Translation/archive/main.zip
      Github repository:
      https://github.com/SkyLundy/Fluency-Translation
      File issues and feature requests here (your feedback and testing is greatly appreciated):
      https://github.com/SkyLundy/Fluency-Translation/issues
       
      Thank you! ¡Gracias! Ich danke Ihnen! Merci! Obrigado! Grazie! Dank u wel! Dziękuję! Спасибо! ありがとうございます! 谢谢你!

    • By snobjorn
      Here's my Norwegian language pack for ProcessWire. I've been adding translations gradually since 2015. By November 2020 the translations are completed, and up to date with the latest dev version of ProcessWire.
      For details, go to the ProcessWire Modules page …
      https://modules.processwire.com/modules/norwegian/
      … and/or GitHub:
      https://github.com/snobjorn/processwire-norwegian-language-pack-nb-no
      Status:
      Completed / up to date.
      Third party and PRO module translations have moved to another repository:
      The site files have been moved to a new repository for module files in Norwegian. Those translations includes translations for some free and some pro modules, see the complete list at GitHub.
    • By Juergen
      Hello @ all,
      I have created an inputfield with a configuration field in the backend where you can set a time format for every language (see screenshot below).

      As you can see both language values (default and German) have the default value(%R), but I have set different values, which were correctly stored in the DB (see screenshot below):

      As you can see the values are '%R' and '%r'.
      I have created the configuration inputfield like this:
      /** @var InputfieldText $f */ $languages = $this->wire('languages'); $f = $this->wire('modules')->get('InputfieldText'); $f->attr('name+id', 'timeformat'); $f->label = $this->_('Timeformat on frontend'); $f->initValue = '%R';//default value $f->attr('value', $this->timeformat ? $this->timeformat : '%R'); $this->message($this->get('timesformat')); if($languages) { $f->useLanguages = true; foreach($languages as $language) { if($language->isDefault()) continue; $f->set("value$language", (string) $this->get("timeformat$language->id")); } } $f->inputType = 'text'; $f->description = $this->_('Please enter the time format that the times should appear on the frontend in strftime format.'); $f->notes = sprintf($this->_('For example shows the time as 08:00, as 08:00 AM. You can find more examples at %s.'), '<a href="https://www.php.net/manual/de/function.strftime.php">https://www.php.net/manual/de/function.strftime.php</a>'); $f->columnWidth = 100; The important part here is:
      if($languages) { $f->useLanguages = true; foreach($languages as $language) { if($language->isDefault()) continue; $f->set("value$language", (string) $this->get("timeformat$language->id")); } } I have borrowed the code from the DateTimeInputfield (https://github.com/processwire/processwire/blob/master/wire/modules/Inputfield/InputfieldDatetime/InputfieldDatetime.module), but the field values will be always populated with the default value ('%R').
      Are I am missing something? Does anyone has experience with multilanguage fields and could help me out?
      Thanks in advance.
    • By Sten
      Hello
      Till now I hacked something with the twig template but it works no more with new PW versions so I look forward to create a module. I am working on a site in multiple languages : French, English, Italian, German, Spanish, Portuguese, Hebrew, Russian. The new posts are entered in any language with a field for language. Till now, I got twig files to get the translations with constants defined for each part of the pages.
      So I'd like to create a module to include theses files added according to the url /fr/en/...
      Have you some observations to do before I begin about the direction to take ?
      Thank you
    • By ICF Church
      Hi 👋
      Anyone else having this problem?
      Requirements:
      - Repeater (matrix & normal) with mutlilanguage fields (text, textarea…) 
      - Backend language set to something other than default (ie. German) 
      Reproduce:
      - Add a new repeater Item (ajax, I found no way to possible to disable it with matrix)

      (Notice how the default language tab is active instead of the backend language…)
      - Write something into the (default language) field
      - Try to save, if field is required, this will not work. If not required, then when reloading, the content will be inside the backend language field, instead of the default language field who was (presumably) active
      Analysis:
      When  loading  a new repeater element with ajax, the default langue tab is active, but the backend language inputfield is visible (with no visual indication). When writing into the field, it will populate the backend language. When manually clicking on the default language tab (which is already active), the field will switch to the actual default language field (which is [now] empty) (that can now be populated…)
      Also Notice, the labels of the elements to be added are in default language as well instead of the translated label (images instead of Bilder)…
      ProcessWire 3.0.148, Profields 0.0.5…
      Is it my system configuration, or does anyone else have the same issue? This is a screen recording of the problem:
      Issue: https://github.com/processwire/processwire-issues/issues/1179

      Screen Recording 2020-02-25 at 14.18.31.mov
×
×
  • Create New...