Instantly share code, notes, and snippets.

What would you like to do?
express + i18n-node + handlebars and avoid concurrency issues
// require modules
var express = require('express'),
i18n = require('i18n'),
hbs = require('hbs'),
app = module.exports = express();
locales: ['en', 'fr'],
cookie: 'locale',
directory: "" + __dirname + "/locales"
app.configure(function () {
// setup hbs
app.set('views', "" + __dirname + "/views");
app.set('view engine', 'hbs');
app.engine('hbs', hbs.__express);
// you'll need cookies
// init i18n module for this loop
// register hbs helpers in res.locals' context which provides this.locale
hbs.registerHelper('__', function () {
return i18n.__.apply(this, arguments);
hbs.registerHelper('__n', function () {
return i18n.__n.apply(this, arguments);
// serving homepage
app.get('/', function (req, res) {
// startup
<span id="text">{{{__ "text to test"}}}</span>
<span id="onecat">{{{__n "%d cat" "%d cats" 1}}}</span>
<span id="twocats">{{{__n "%d cat" "%d cats" 2}}}</span>

This comment has been minimized.

Ajar-Ajar commented Jan 17, 2015

Hi @mashpie
Are there any other examples for using handlebars with i18n-node, this is great for a first "hello world" example but what about real life examples? different grammar, hence different word locations in different locales etc... it would also help to see along with i18n configuration+route logic+view template - the generated json file for static text and working along with dynamic data localized text coming from the db.
This is what developers will end up wanting to do pretty quickly while localizing an app and the example is leaving you to guess all of these trivial parts...


This comment has been minimized.

gmunumel commented Jun 27, 2015

@Ajar-Ajar, second that. I'm using cordova, closure.js, handlebars and i18n for a project. So far, it's quite difficult to integrate i18n with closure.js. @mashpie, is there any way to get this working with those libraries?


This comment has been minimized.

ehynds commented Aug 20, 2015

How are those two Handlebars helpers defined in the res.local context? They're outside of any middleware.


This comment has been minimized.

DJviolin commented Mar 22, 2016

@mashpie Unfortunately my implementation following this tutorial doesn't work. Default Hungarian translation works, but any content from /locales/en.json file never used:


var express        = require('express'),
    bodyParser     = require('body-parser'),
    cookieParser   = require('cookie-parser'),
    exphbs         = require('express-handlebars'),
    i18n           = require('i18n');
var app = express();

app.engine('.hbs', exphbs({
  extname: '.hbs',
  defaultLayout: 'main',
  helpers: {
    __: function() { return i18n.__.apply(this, arguments); },
    __n: function() { return i18n.__n.apply(this, arguments); }
app.set('view engine', '.hbs');

app.use(bodyParser.urlencoded({ extended: false }));

  locales: ['hu', 'en'],
  fallbacks: {'en': 'hu'},
  defaultLocale: 'hu',
  cookie: 'locale',
  queryParameter: 'lang',
  directory: __dirname + '/locales',
  directoryPermissions: '755',
  autoReload: true,
  updateFiles: true,
  api: {
    '__': '__',  //now req.__ becomes req.__
    '__n': '__n' //and req.__n can be called as req.__n

app.use('/', require('./routes/portfolio'));


<span id="text">{{{__ "text to test"}}}</span>


    "text to test": "text to test on hungarian"


    "text to test": "text to test on english"


Solved with placing i18n's code in front of the routers and I activating the language switch simply with cookies:

app.get('/hu', function (req, res) {
  res.cookie('locale', 'hu', { maxAge: 900000, httpOnly: true });
app.get('/en', function (req, res) {
  res.cookie('locale', 'en', { maxAge: 900000, httpOnly: true });

This comment has been minimized.

DJviolin commented Mar 23, 2016

@mashpie This way my translation called only with cookies, no way to know from the urls which language is used. url can be both hungarian and english translated page, depends on the cookie. Is it problem for search engines, like Google?


This comment has been minimized.

eloquence commented Jun 16, 2016

I had to move the helpers into a middleware, or all messages resolved in the context of {{#each}} loops were output in the default locale, with the debug message, "WARN: No locale found - check the context of the call to __(). Using en as current locale" (the value of this being set to the message key inside the loop). Please let me know if there's a more elegant way to do this:

app.use(function(req, res, next) {
  hbs.registerHelper('__', function() {
    return i18n.__.apply(req, arguments);
  hbs.registerHelper('__n', function() {
    return i18n.__n.apply(req, arguments);

UPDATE: Don't do what I did -- re-registering with hbs on each request creates concurrency issues. Indeed, doing this inside of middleware is not necessary at all, as hbs has access to the current locale through the options parameter that gets passed to each helper. The solution I ultimately went with can be found here (see the __ and __n helpers in particular):


This comment has been minimized.

ekkis commented Oct 14, 2016

I'm confused. the title of this document reads "express + i18n-node + handlebars", referring to i18n-node, as opposed to i18n which is what is shown as required. which module does this apply to? because both exist. at first I installed i18n-node and then thought that i18n was required so I uninstalled the former and installed the latter. in neither case can I make this work. which is the correct module?


This comment has been minimized.

JailBreakC commented Oct 20, 2016

@eloquence thanks a lot! your method is fucking working! solved my problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment