5

Mustache 仕様と互換性のある Hogan.js を使用しています。そして、複数形化を行う確実な方法を実装するのに苦労しています。今後も Hogan を使用し、i18n の取り扱いにはhttp://i18next.com/を使用したいと思います

このようなことをすると、単純なケースで機能します

タイトル:

{{#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) など) をすべて生成できるように、別の手順で解析/スキャン/レンダリングする必要がありますが、サーバーの起動時に 1 回だけ実行する必要があります。

これは次のようなもので壊れます

{{#plural(key.nested)}}

データが次のように見える場合、それは一致します

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

これには、コンテキストから値を手動で検索する必要もありますが、大きな問題ではありませんが、解決できない可能性のあるラムダ/パーシャルのケースがいくつかあります

デフォルトの翻訳マッピングの場合、物事はそれほど複雑ではなく、扱いも簡単です

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キーをパターンに一致するi18n 場所に置き換えますn/i18n .+/

などを使用{{#i18n {count: count, text: 'I have <%count%> 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)));';
}

i18nHogan.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 に答える