Javascript 如何在霍根处理多元化

Javascript 如何在霍根处理多元化,javascript,mustache,hogan.js,plural,i18next,Javascript,Mustache,Hogan.js,Plural,I18next,我使用的是Hogan.js,它与Mustache规范兼容。 我在实施多元化的坚实方法方面遇到了困难。 我想继续使用Hogan并用于i18n处理 这样做对简单的情况有效 第三方物流: 数据: 这需要在单独的步骤中解析/扫描/呈现,以便能够生成所有所需的复数方法(复数(key.val)等),但这很好,只需要在服务器启动时执行一次 这会破坏像这样的事情 {{{#复数(key.nested)} 如果数据看起来像 { 'plural(key': { 'val)': ... } } 这还需

我使用的是Hogan.js,它与Mustache规范兼容。 我在实施多元化的坚实方法方面遇到了困难。 我想继续使用Hogan并用于i18n处理

这样做对简单的情况有效

第三方物流:

数据:

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

这会破坏像这样的事情

{{{#复数(key.nested)}

如果数据看起来像

{
  'plural(key': {
    'val)': ...
  }
}
这还需要我从上下文中手动查找值,这不是一个大问题,但在某些情况下,lambda/partials可能无法解决


对于默认的转换映射,事情要简单得多,这很容易处理

好的,我认为解决这个问题的最佳方法是:

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);
更改树,将所有
标记
键替换为
i18n
其中
n
与您的模式匹配
/i18n.+/

我使用
{{{i18n{count:count,text:'I have apples!'}}
等添加i18next的选项 因此,我将所有的
n
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
中,您可以访问模板的所有方法

一些Mustache实现可以处理此问题:@Gwendal Roué谢谢。我在发布之前也找到了它。这就是我的示例代码的来源。然而,在lambda的上下文中,如果没有渲染器,就很难做到这一点,而且lib不是javascript(更清楚地说,我将添加javascript作为标记),谷歌搜索“mustachetemplate pluralization”也会产生一些其他结果。。。“你能在那里找到解决办法吗?”格温达尔·鲁埃我读了所有我能找到的,但没有一个解决办法考虑到多元化。如果他们这样做,将导致重新呈现处理过的模板,另一(2)次时间看起来是功能请求的时间:-)
Hogan.codegen.i18n = function (node, context) {
  context.code += 't.b(t.v(t.i18n("' + esc(node.n) + '",c,p,0)));';
}
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
};