How to handle pluralization in Hogan

I use Hogan.js, which is compatible with the Mustache specification. And they fail to implement a solid way to do pluralization. I would like to continue using Hogan and use http://i18next.com/ to handle i18n

something like this works for simple cases

TPL:

{{#plural(count)}}
  I have {{count}} apples!
{{/plural(count)}}

Data:

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

this requires parsing / scanning / rendering in separate steps in order to be able to generate all the necessary plural methods (plural (key.val), etc.), but this is fine, it needs to be done only once, when the server boots up.

it breaks things like

{{# plural (key.nested)}}

which would match if the data looked like

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

, , , lambda's/partials, .

, ,

+4
1

, , :

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

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

0

All Articles