Closed babiz closed 9 years ago
It's in the readme: https://github.com/ericf/express-handlebars#helpers
You can access handlebars
on the ExpressHandlebars
instance: https://github.com/ericf/express-handlebars#handlebarsrequirehandlebars
@babiz Did you figure out how to create your helper? I tried the following but it doesn't seem to work:
// Configure i18n
i18n.configure({
locales: ['en', 'fr'],
defaultLocale: 'en',
directory: __dirname + '/locales'
});
app.use(i18n.init);
// Configure view engine
var hbs = expressHandlebars.create({
extname: '.hbs',
layoutsDir: path.join(__dirname, 'views/email'),
defaultLayout: 'layout',
helpers: {
i18n: function () { return i18n.__.apply(this, arguments); }
}
});
I'm very close since i18n is being called but it doesn't seem to know what is the current locale. Right now I have everything in English even after forcing the locale to be French.
Hmm. I got it working by using req
which contains the locale of the user. I'd be happy to know if there is a better way.
// Configure view engine
var hbs = expressHandlebars.create({
extname: '.hbs',
layoutsDir: path.join(__dirname, 'views/email'),
defaultLayout: 'layout'
});
// Add i18n helper to handlebars
app.use(function (req, res, next) {
hbs.handlebars.registerHelper('i18n', function () {
return i18n.__.apply(req, arguments);
});
next();
});
Also, I think it'd be nice to add the solution to the documentation. Or even better, add i18n support into this library.
Yes Gzurbach. I tried to use the registerhelper but it did not work for me. Not sure what I was doing wrong so I did the following and it is working fine.
var hbs = exphbs.create({
defaultLayout: 'main',
extname: '.html',
layoutsDir: path.resolve('./app/admin/views/layouts'),
helpers: {
__: function (textToBeTranslated) {
return i18n.__(textToBeTranslated);
},
}
});
Reference express-hbs 's helper
args = Array::slice.call(arguments)
options = args.pop()
i18n.__.apply options.data.root, args
I could not get registerHelper working with this. Could you please show me how to registerHelper. I am trying to use it with i18n module.