Skip to content

Instantly share code, notes, and snippets.

@kindy
Created December 4, 2013 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kindy/7786294 to your computer and use it in GitHub Desktop.
Save kindy/7786294 to your computer and use it in GitHub Desktop.
mustache i18n support in django
var mus = require('mustache');
var t = npgettext("abcadfadf a", "%(count)d app", "%(count)d apps", count);
function gettext_plural() {
return function(text, render) {
try {
var ctx = JSON.parse(text);
var count = parseInt(render(ctx[0]), 10);
return render(count > 1 && ctx[2] ? ctx[2] : ctx[1]);
} catch (ex) {
return '';
}
}
}
(function() {
var oldMake = mus.Context.make;
var Context = mus.Context;
var ctx = new Context({gettext_plural: gettext_plural});
Context.make = function(view) {
return (view instanceof Context) ? view : new Context(view, ctx);
};
})();
/*
=> tmpl
{{# _ }}{{app_num}} App{{ plural "{{app_num}}" }}{{app_num}} Apps{{/_}}
=> parse_result
-> count_id
-> text
-> text_plural
=> output
'[[#gettext_plural]]%s[[/gettext_plural]]' %
json_encode([
count_id,
translation.ungettext(text, text_plural, 1),
translation.ungettext(text, text_plural, 2)
])
*/
console.log(
mus.render(
'{{#apps}} * {{#gettext_plural}}["{{app_num}}", "{{app_num}} App", "{{app_num}} Apps"]{{/gettext_plural}}\n{{/apps}}',
{ apps: [{app_num: 4}, {app_num: 1}] }
),
mus.render(
'{{#gettext_plural}}["{{app_num}}", "{{app_num}} App", "{{app_num}} Apps"]{{/gettext_plural}}\n',
{app_num: 4}
),
mus.render(
'{{#gettext_plural}}["{{app_num}}", "{{app_num}} App", "{{app_num}} Apps"]{{/gettext_plural}}\n',
{app_num: 1}
)
);
import re
con_re = re.compile(r'\{\{#(plural|count|context)#\}\}')
def get(txt):
ctx = con_re.split(txt)
ret = dict(msg=ctx.pop(0))
ret['single'] = ret['msg']
if not ctx:
return ret
for idx in range(0, len(ctx), 2):
ret[ctx[idx]] = ctx[idx + 1]
return ret
print get('''{{count}} app.{{#plural#}}{{count}} apps.{{#count#}}{{count}}''')
print get('''{{count}} app.''')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment