5

我正在使用与 Mustache 规范兼容的 Hogan.js。而且我在实施一种可靠的多元化方式时遇到了麻烦。我想继续使用 Hogan 并使用http://i18next.com/进行 i18n 处理

做这样的事情适用于简单的情况

tpl:

{{#plural(count)}}
  I have {{count}} apples!
{{/plural(count)}}

数据:

{
  count: 2,
  'plural(count)': function () {
    return function () {
      return _t[arguments[0].trim()][this['count']]
    }
  }
}

这需要在单独的步骤中进行解析/扫描/渲染,以便能够生成所有必需的复数方法(plural(key.val) 等),但这很好,它只需要在服务器启动时完成一次。

这打破了像

{{#plural(key.nested)}}

如果数据看起来像,那将匹配

{
  'plural(key': {
    'val)': ...
  }
}

这也需要我手动从上下文中查找值,这不是一个主要问题,但在某些情况下可能无法解决 lambda/partials

对于默认的翻译映射,事情要简单得多,而且很容易处理

4

1 回答 1

0

好的,找到了我认为最好的方法来处理这个问题:

var tpl_data = fs.readFileSync('./tpl/test.hjs', 'utf8');
var scan = Hogan.scan(tpl_data);
var tree = Hogan.parse(scan);
var gen = Hogan.generate(tree, tpl_data, {asString:false});
var out = gen.render(data);

更改树,将所有tag键替换i18nn与您的模式匹配的位置/i18n .+/

我使用{{#i18n {count: count, text: 'I have <%count%> apples!'} }}等来添加 i18next 的选项,所以我匹配 alln的开头i18n

添加i18n到 Hogan.codegen

Hogan.codegen.i18n = function (node, context) {
  context.code += 't.b(t.v(t.i18n("' + esc(node.n) + '",c,p,0)));';
}

i18n方法添加到 Hogan.Template 的原型中

Hogan.Template.prototype.i18n = function (key, ctx, partials, returnFound) {
  //here the ctx is an array with from right to left the render scopes
  // most right is the most inner scope, most left is the full render data
  //1. get the config from the key, 
  //2. get the values out of the scope
  //3. get the values for the translation
  //4. lookup the translation, and repleace the values in the translation
  //5. return the translated string
};

请注意,Hogan.Template.prototype.i18n您可以在其中访问模板的所有方法

于 2013-12-24T23:40:47.783 回答