Search code examples
localizationfirefox-os

How to switch languages in Firefox OS apps?


I need to support my app for multiple languages and I want to provide the user a feature to select a language from a dropdown.

For now, I am working on the Firefox OS Boilerplate app and I have added a <select> in the homescreen as follows:

<p>
    <label data-l10n-id="language">Language: </label>
    <select id="language">
        <option value="en">English</option>
        <option value="fr">French</option>
        <option value="es">Spanish</option>
    </select>
</p>

I have also setup a simple event listener for it in vanilla JS.

I searched the MDN docs but I did not find anywere mentioned about switching the language.

Can you please guide me as in how to change the language in the Firefox OS app programatically?


Solution

  • One approach is the one you are using, let the user decide the language for the application. You could store the user's selection somewhere in the app (localStorage for example) and, when loading a page, check the language value and take the appropriate actions to show all text in that language. To implement this without using an external library you could have a global object with all the translations:

    var translations = new Object();
    translations.en = {
        text1: 'The first text',
        text2: 'The second text'
    };
    translations.es = {
        text1: 'El primer texto',
        text2: 'El segundo texto'
    };
    

    And your page looks like this:

    <span data-translate="text1"></span>
    <span data-translate="text2"></span>
    

    So, after loading a page and having the language selected by the user in a variable (let's say lang), you iterate over all the elements that have the data-translate attribute and set their content dynamically.

    var items = document.querySelectorAll('[data-translate]');
    for (var i = 0; i < items.length; ++i) {
        var index = items[i].getAttribute('data-translate');
        items[i].innerHTML = translations[lang][index];
    }
    

    Another approach is using a library that detects the user's language automatically (from the system's language) and replaces all translatable elements from the page (you mark these) with the corresponding values (which are stored in a separate file). For example, check webL10n.

    I believe you can implement the first approach more easily using webL10n, you should check it out.