【问题标题】:i18n-node-2, Express and a Handlebars helperi18n-node-2,Express 和 Handlebars 助手
【发布时间】:2015-10-23 04:23:35
【问题描述】:

我正在尝试为i18n-node-2 创建一个 Handlebars 助手,以便我可以直接从视图中使用本地化字符串,但是首先使用 Express 助手注册 i18n,然后我无法获得我可以在 helper 中使用 i18n。

相关代码:

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);
});

基本上,在助手内部,我需要由i18n.expressBind() 创建的i18n 实例,它调用i18n.init()。除了修改源代码返回这个实例,有没有其他方法可以获取?

【问题讨论】:

    标签: node.js express handlebars.js


    【解决方案1】:

    回答我自己的问题。 i18n-node-2 将查找函数 ____n 放在 locals 集合中,您可以从 Handlebars 在运行帮助程序时为您提供的上下文中获取:

    hbs.registerHelper('__', function(key, context) {  
      return context.data.root.__(key);
    });
    

    .. 这是一种享受。

    【讨论】:

      【解决方案2】:

      以@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);
      });
      

      【讨论】:

        猜你喜欢
        • 2015-05-25
        • 1970-01-01
        • 2016-12-04
        • 2015-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多