Skip to content

Instantly share code, notes, and snippets.

@mrrovot
Forked from mashpie/i18n-express-hbs-app.js
Created October 4, 2018 00:11
Show Gist options
  • Save mrrovot/a1f0311e20bf0a382c0d163a4d381c90 to your computer and use it in GitHub Desktop.
Save mrrovot/a1f0311e20bf0a382c0d163a4d381c90 to your computer and use it in GitHub Desktop.
express + i18n-node + handlebars and avoid concurrency issues
// require modules
var express = require('express'),
i18n = require('i18n'),
hbs = require('hbs'),
app = module.exports = express();
i18n.configure({
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
app.use(express.cookieParser());
// init i18n module for this loop
app.use(i18n.init);
});
// 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) {
res.render('index');
});
// startup
app.listen(3000);
<span id="text">{{{__ "text to test"}}}</span>
<br>
<span id="onecat">{{{__n "%d cat" "%d cats" 1}}}</span>
<br>
<span id="twocats">{{{__n "%d cat" "%d cats" 2}}}</span>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment