简体   繁体   中英

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.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM