Saltearse al contenido

Translation service

Esta página aún no está disponible en tu idioma.

Zumito comes with a localization system by default.

Define translations

The first step to start using the translations system is to register some texts. to do so, simply create a json file on the translations folder of your bundle with the name of the lang in ISO 639-1 format

Examples:

  • Directorysrc
    • Directorymodules
      • Directoryexample
        • Directorytranslations
          • en.json
          • es.json
          • DirectoryexampleSubkey2
            • en.json
            • es.json

Then in the json just write your text with a key.

en.json

{
"examplePhrase1": "This is an example phrase",
"exampleSubkey1": {
"examplePhrase2: "This is an example phrase with a subkey"
}
}

es.json

{
"examplePhrase1": "Esta es una frase de ejemplo",
"exampleSubkey1": {
"examplePhrase2: "Esta es una frase de ejemplo con una subclave"
}
}

exampleSubkey2/en.json

{
"examplePhrase3": "This is an example phrase within a subfolder"
}

Obtain translations

Now we have set some translations let’s obtain the translated text. To do so, first we need to import the translator service. To do so, first we need to import the serviceContainer like here:

import { ServiceContainer } from 'zumito-framework';

then in our code import the translator service:

const translator = ServiceContainer.getService('TranslationManager');

And get your translated texts by the key and language:

translator.get('examplePhrase1', 'en'); // returns "This is an example phrase"
translator.get('exampleSubkey1.examplePhrase1', 'es'); // returns "Esta es una frase de ejemplo con una subclave"
translator.get('exampleSubkey2.examplePhrase3', 'en'); // returns "This is an example phrase within a subfolder"

Translation variables

Somethings translations need to have variable text, like user info or other data. You can define a text with one or multiple variables encapsulated with brakets:

en.json

{
"welcome": "hi {user}, have a nice day!",
}

then you can get the translation like this:

translator.get('welcome', 'en', {
user: "Zumito"
}); // returns "hi Zumito, have a nice day!"