Using the plugin – Multilanguage support!

To start using our files, you must tell your ViewModel components which language to use. We will perform this operation at constructor method; check out this example:

import {I18N} from 'aurelia-i18n';
import { inject } from 'aurelia-dependency-injection';

@inject(I18n) export class WelcomePageComponent { constructor(i18n) { this.i18n = i18n; this.i18n
.setLocale('es-ES')
.then( () => {}); } ... }

What if you want to get the active locale? Easy, change the configuration file to look like this:

import {I18N} from 'aurelia-i18n';
@inject(I18n) export class WelcomePageComponent { constructor(i18n) { this.i18n = i18n; } ... }

Similar to setLocale(), we have the getLocale() method. You can retrieve the active locale by typing the following:

console.log(this.i18n.getLocale());

Now, on the HTML file, we just need to call our translation aliases to map the properties we have defined in our translation.json files:

<h2 t="welcome">Welcome to FIFA WX 18</h2>

Optionally, we are able to use our second alias to map values:

<h2 i18n="welcome">Welcome to FIFA WX 18</h2>

Now you are ready to start adding multiple language support for your application! There are so many other advanced hints to get the best results using this plugin. We will show you one of them up next.

Imagine that you need to map <html> tags in your translation files. Is that possible? Yes. Imagine you need to render some long test (a product description, for example) and need to bold just a few words like price or discount. What do we need to do? Very easy, just add the HTML tag you need:

"time_remaining": "Time remaining : <b>{{time}}</b>"

Now, let's use this in our View file:

<label t="time_remaining">Time remaining : {{time}}</label>

If you look at your window, you'll see something like &lt;b&gt;bold&lt;/b&gt;; don't be scared, it's normal. It's because we didn't set the correct markup to make our HTML tag correctly interpreted. You must know that there are four main attributes to add custom behavior to our translation file variables:

  • [text]: Default attribute, escapes the tag value as simple text
  • [html]: Tells our translation file "Hey, this contains HTML tags, render it as them!"
  • [append]: Appends the translation to the current content already present in the element (allows HTML)
  • [prepend]: Prepends the translation to the current content already present in the element (allows HTML)

This attribute has to be before our translation identifier key. You know what to do next:

<label t="[html]time_remaining">Time remaining : {{time}}</label>

Awesome? Yes, it is. It's up to you to research about other more advanced features; we are very sure you will enjoy all the options that i18n offers. That's all for this chapter? Of course, no. Let's keep exploring!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.116.43