2013-12-16 38 views
4

我正在使用Hogan.js,它與Mustache規範兼容。 而即時通訊實施複雜性的一個堅實的方式困難。 我想用霍根保持和使用http://i18next.com/的國際化處理如何處理Hogan中的多元化

做這樣的事情的工作原理很簡單案件

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)等)但那很好,它只需要在服務器啓動時完成一次。

這打破的東西像

{{#plural(key.nested)}}

如果數據看起來像

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

,將匹配這也需要我手動查找上下文中的值,這不是一個主要問題,但有些lambda/partials可能無法解決的情況。

默認轉換映射,東西少了很多複雜的,並且那好辦

+0

一些小鬍子的實現可以處理這個:https://github.com/groue/GRMustache/issues/50 –

+0

@GwendalRoué謝謝。我發現之前也發現它。那就是我的示例代碼來自哪裏。但是,在lambda的上下文中很難做到沒有渲染器,並且lib不是javascript(我將添加javascript作爲標記,更清晰) –

+0

谷歌搜索「鬍鬚模板複數化」會產生一些其他的結果......你不會在那裏找到解決方案嗎? –

回答

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); 

改變樹,更換所有tagi18n 其中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)));'; 
} 

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所有模板的方法