我试图为i18n-node-2创建一个Handlebars helper,以便我可以直接从视图中使用本地化的字符串,但是使用Express helper首先注册i18n,然后我无法获得i18n的实例,我可以在helper中使用。
相关代码:
var i18n = require('i18n-2');
用Express注册i18n:
i18n.expressBind(app, {
locales: ['en', 'de'],
cookieName: 'locale',
extension: ".json"
});
创建我的助手:
hbs.registerHelper('__', function() {
// What I would *like* to do, but the 'i18n' instance here is the wrong one
return i18n.__.apply(i18n, arguments);
});
基本上,在helper中,我需要由i18n.expressBind()
创建的i18n实例,它调用i18n.init()
。如果不修改源代码来返回这个实例,还有其他方法可以得到它吗?
回答我自己的问题。i18n-node-2将查找函数__
和__n
放在locals集合中,您可以在运行helper时从Handlebars提供的上下文中获得它们:
hbs.registerHelper('__', function(key, context) {
return context.data.root.__(key);
});
. .
要构建@SteveHobbs的答案,如果您有一个期望任意数量的参数甚至选项哈希的助手,您可以执行以下操作:
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);
});