如何在 Hogan 中处理多元化

Pau*_*ema 5 javascript plural mustache hogan.js i18next

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

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

tpl:

{{#plural(count)}}
  I have {{count}} apples!
{{/plural(count)}}
Run Code Online (Sandbox Code Playgroud)

数据:

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

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

这打破了像

{{#plural(key.nested)}}

如果数据看起来像

{
  'plural(key': {
    'val)': ...
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Pau*_*ema 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);
Run Code Online (Sandbox Code Playgroud)

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

我使用{{#i18n {count: count, text: 'I have <%count%> apples!'} }}等来添加 i18next 的选项,这样我就匹配所有ni18n

添加i18n到 Hogan.codegen

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

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
};
Run Code Online (Sandbox Code Playgroud)

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