Reputation: 3326
I'm trying to create a Handlebars helper for i18n-node-2 so that I can use localised strings directly from the view, but using the Express helper to register i18n in the first place, I can't then get an instance of i18n that I can use inside the helper.
The relevant code:
var i18n = require('i18n-2');
Registering i18n with Express:
i18n.expressBind(app, {
locales: ['en', 'de'],
cookieName: 'locale',
extension: ".json"
});
Creating my helper:
hbs.registerHelper('__', function() {
// What I would *like* to do, but the 'i18n' instance here is the wrong one
return i18n.__.apply(i18n, arguments);
});
Basically, inside the helper I need the the instance of i18n as created by i18n.expressBind()
, which calls i18n.init()
. Short of modifying the source code to return this instance, is there another way to get it?
Upvotes: 0
Views: 725
Reputation: 6605
To build off of @SteveHobbs' answer, if you have a helper that's expecting an arbitrary number of parameters and even an options hash, you could do the following:
hbs.registerHelper('foo', function() {
var args = Array.prototype.slice.call(arguments),
last = args.pop(),
options = last.hash,
context = last.data.root;
// Show what's available:
console.log('From foo helper:');
console.log('args:', args);
console.log('options:', options);
console.log('context:', context);
});
Upvotes: 0
Reputation: 3326
Answering my own question. i18n-node-2 places the lookup functions __
and __n
in the locals collection, which you can get to from the context that Handlebars gives you when running the helper:
hbs.registerHelper('__', function(key, context) {
return context.data.root.__(key);
});
.. which works a treat.
Upvotes: 0