Mastering Web Application

(Rick Simeone) #1

Building AngularJS Web Applications for an International Audience


The exact technology to be used to translate partials during the build time will
depend on the build system used. For the Grunt.js based builds we could use
Grunt's capability of creating templates. Considering the following partial, named
hello.tpl.html:


<div>
<h3>Hello, {{name}}!</h3>
<input ng-model='name' placeholder='Provide name here'>
</div>

We could turn it into Grunt.js template to be processed during the build-time:


<div>
<h3><%= greeting.hello %>, {{name}}!</h3>
<input ng-model='name' placeholder='<%= input.name %>'>
</div>

Then, based on a list of supported locales and translation files, the Grunt.js build
would produce translated partials, saving them in folders corresponding to a locale
name. For example:


/en-us/hello.tpl.html
/fr-ca/hello.tpl.html
/pl-pl/hello.tpl.html

Setting up a build-time translation system might be a bit cumbersome, but usually
it is a one-time effort done at the very beginning of a project. The benefit is that we
avoid any kind of performance problems linked to localization, and can translate
strings at any place of a partial.


Handling translated strings used in the


JavaScript code


While most of the strings to be translated are located in AngularJS templates, there
are times when we need to handle text in a JavaScript code. We might need to
display a localized error message, an alert and so on. Whatever the reason may be,
we need to be prepared for handling translated strings in the JavaScript code.


AngularJS doesn't provide any facility that would help us here, so we need to roll up
our sleeves, and write a simple service that will serve us as a handy translation tool.
Before writing any code let's consider an example usage scenario. Let's say we would
like to prepare an alert message to be displayed when an item is successfully deleted
from a persistent store, doesn't exist in a persistent store, and so on.

Free download pdf