Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use i18n with Node.js?

We are about to start building our web app in Node.js and I would like to be ready for i18n so I'm looking for your experience with building Node.js apps where the text is translatable.

Preferably I'd like to use a tool like Pootle via Git or other if you have any recommendations.

like image 392
webjay Avatar asked Jan 23 '12 13:01

webjay


1 Answers

There are a number of i18n modules you can use in your application, but you can create your own if you want.

For example create a folder /languages and inside it create en.js, fr.js etc

it.js

module.exports = {
  "name": "nome",
  "age": "eta",
  .. etc
}

The important thing is to set a default language and make a language select bar somewhere in your site. When the user chooses another language (and not English) in your app you do something like this:

app.get('/lang/:ln', function (req, res, next) {
  // remember the user's chosen language
  req.session.language = req.params.ln;
});

Then you can have a language helper function like so:

translate = function (language, text) {
  // language array contains all the languages
  return language_array[language].text;
}
// example: translate(req.session.language, "age")
like image 191
alessioalex Avatar answered Oct 26 '22 11:10

alessioalex