If your app will touch people or systems from all over the world, internationalization and localization (i18n) may be an important part of your international strategy. Sails provides built-in support for detecting user language preferences and translating static words/sentences thanks to i18n-node. (npm).
In a view:
<h1> <%= __('Hello') %> </h1>
<h1> <%= __('Hello %s, how are you today?', 'Mike') %> </h1>
<p> <%= i18n('That\'s right-- you can use either i18n() or __()') %> </p>
In a controller or policy:
req.__('Hello'); // => Hola
req.__('Hello %s', 'Marcus'); // => Hola Marcus
req.__('Hello {{name}}', { name: 'Marcus' }); // => Hola Marcus
Or if you already know the locale id, you can translate from anywhere in your application using sails.__
:
sails.__({
phrase: 'Hello',
locale: 'es'
});
// => 'Hola!'
See Concepts > Internationalization > Locales.
Settings for localization/internationalization may be configured in sails.config.i18n
. The most common reason you'll need to modify these settings is to edit the list of your app's supported locales and/or the location of your translation stringfiles:
// Which locales are supported?
locales: ['en', 'es'],
// Where are your locale translations located?
localesDirectory: '/config/locales'
Of course you can always require()
any Node modules you like, anywhere in your project, and use any internationalization strategy you want.
But worth noting is that since Sails implements node-i18n integration in the i18n hook, you can completely disable or override it using the loadHooks
and/or hooks
configuration options.
See Concepts > Internationalization > Translating dynamic content.
The above technique works great out of the box for server-side views. But what about rich client apps that serve static HTML templates from a CDN or static host? (e.g. performance-obsessed SPAs or PhoneGap apps/Chrome extensions)
There are lots of different options available for client-side internationalization. Like other client-side technologies, you should have no problem integrating any of them with Sails.
If you'd prefer not to use an external internationalization library, you can actually reuse Sails' i18n support to help you get your translated templates to the browser. If you want to use Sails to internationalize your client-side templates, put your front-end templates in a subdirectory of your app's
/views
folder.
- In development mode, you should retranslate and precompile your templates each time the relevant stringfile or template changes using grunt-contrib-watch, which is already installed by default in new Sails projects.
- In production mode, you'll want to translate and precompile all templates on lift(). In loadtime-critical scenarios (e.g. mobile web apps) you can even upload your translated, precompiled, minified templates to a CDN like Cloudfront for further performance gains.