Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Image Added

Figure 1: App Locale Changes Automatically Based on Browser's Locale

aa

Code Block
languagexml
titleSub Header
linenumberstrue
<div id="languages">
    <li><a onClick="switchLanguage('en_US'); return false;" class="btn waves-effect btn waves-button waves-float"><img title="English" src="#appResource.US-United-States-Flag-icon.png#"/></a></li>
    <li><a onClick="switchLanguage('pt'); return false;" class="btn waves-effect btn waves-button waves-float"><img title="Portuguese" src="#appResource.PT-Portugal-Flag-icon.png#"/></a></li>
    <li><a onClick="switchLanguage('fr'); return false;" class="btn waves-effect btn waves-button waves-float"><img title="French" src="#appResource.FR-France-Flag-icon.png#"/></a></li>
</div>


This is the script responsible in getting the browser's locale and reloads the current page to the new locale if there's a match in languages supported by the app.

Code Block
languagejs
titleCustom Javascript
linenumberstrue
function getLang() {
  if (navigator.languages != undefined) 
    return navigator.languages[0]; 
  return navigator.language;
}

function switchLanguage(lang){
    $.cookie("language", lang);
    
    currentAddress = this.location.href;
    newAddress = removeParameterFromUrl(currentAddress, "_lang");
    
    if(newAddress.indexOf("?") > 0){
        newAddress += "&_lang=" + lang;
    }else{
        newAddress += "?_lang=" + lang;
    }

    this.location = newAddress;
}

function removeParameterFromUrl(url, parameter) {
  return url
    .replace(new RegExp('[?&]' + parameter + '=[^&#]*(#.*)?$'), '$1')
    .replace(new RegExp('([?&])' + parameter + '=[^&]*&'), '$1');
}

currentUserLocale = "#currentUser.locale#"; //logged in user profile locale

supportedLanguages = ["en_US","fr","pt","zh_CN"];

$(function(){
    $("#page > header > div.navbar-inner > div > div.nav-no-collapse.header-nav > ul").prepend( $("#languages li") );
    
    //if user profile has no locale set, attempts to retrieve browser's locale and set
    if( currentUserLocale != "" && supportedLanguages.includes(getLang().substring(0,2)) && $.cookie("language") == null){
        
        language = supportedLanguages.filter(
            function(value, index, array){
                return value.substring(0,2) == getLang().substring(0,2);
            } 
        );
        
        switchLanguage( language[0] );
    }
});


aa

View file
nameAPP_userLocaleDemo-1-20211111224220.jwa
height250