如何处理霍根的多元化

How to handle pluralization in Hogan

本文关键字:多元化 处理 何处理      更新时间:2023-09-26

我使用的是Hogan.js,它与Mustache规范兼容。我在实现多元化的坚实道路上遇到了困难。我想继续使用霍根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']]
    }
  }
}

这需要在单独的步骤中解析/扫描/呈现,以便能够生成所有所需的多个方法(复数(key.val)等),但没关系,只需要在服务器启动时完成一次。

这会破坏之类的东西

{{#multiple(key.nested)}}

如果数据看起来像

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

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

对于默认的转换映射,事情要复杂得多,而且处理

很容易

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

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密钥替换为i18n其中n与您的图案/i18n .+/ 匹配

我使用{{#i18n {count: count, text: 'I have <%count%> apples!'} }}等为i18next添加选项所以我匹配所有从i18n 开始的n

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中,您可以访问模板的所有方法