Permalink
Browse files

prototype of i18n features

  • Loading branch information...
shaunlee committed May 2, 2011
1 parent 869b1ec commit 6e46196b40ad75e4148528d83894d9e1731d0b5e
Showing with 30 additions and 7 deletions.
  1. +23 −2 lib/i18n.js
  2. +7 −5 lib/jst.js
View
@@ -1,7 +1,28 @@
// i18n
-// _(ctx)
+exports.locale = '';
+
+/**
+ * gettext('Hello {name}', {name: 'jst'})
+ */
exports.gettext = function(ctx, args) {
- return ctx; // TODO:
+ // TODO:
+
+ for (var name in args) {
+ var re = RegExp('\\{' + name + '\\}', 'g');
+ ctx = ctx.replace(re, args[name]);
+ }
+ return ctx;
+}
+
+/**
+ * ngettext('There is a template', 'There are {n} templates', n)
+ */
+exports.ngettext = function(singular, plural, n) {
+ var ctx = n === 1 ? singular : plural;
+
+ // TODO:
+
+ return ctx.replace(/\{n\}/g, n);
}
View
@@ -38,6 +38,7 @@ exports.addFilters = function(newFilters) {
// compiler
const prefixes = {
+ n: {s: '"', c: '', v: ''},
s: {s: '', c: '"; ', v: '" + '},
c: {s: ' out += "', c: ' ', v: ' out += '},
v: {s: ' + "', c: '; ', v: ' + '},
@@ -46,25 +47,26 @@ const prefixes = {
codere = /\{[%\{] (.+?) [%\}]\}/g;
var compile = exports.compile = function(ctx) {
- var m, i = 0, code = 'var out = "', last = 's';
+ var m, i = 0, code = 'var out = ', last = 'n';
_options.useIt = /{{ (e\()?it\./.test(ctx);
ctx = ctx.replace(/[\t\r\n]/g, '').replace(/\{#.+?#\}/g, '')
if (!_options.useIt) {
- code += '"; with(it) {';
+ code += '""; with(it) {';
last = 'c';
}
while ((m = codere.exec(ctx)) !== null) {
- if (m.index > 0) {
+ if (m.index > 0 && m.index > i) {
code += prefixes[last]['s'] + ctx.substring(i, m.index).replace(/"/g, '\\"');
last = 's';
}
if (m[0].indexOf('{%') === 0) {
code += prefixes[last]['c'] + m[1];
+ if (/\)$/.test(m[1])) code += ';';
last = 'c';
} else if (m[0].indexOf('{{') === 0) {
code += prefixes[last]['v'] + filters.convert(m[1]);
@@ -87,10 +89,10 @@ var compile = exports.compile = function(ctx) {
code += 'return out;';
//console.log(code);
- var fn = new Function('it, _, filters', code);
+ var fn = new Function('it, _, _n, filters', code);
return function(args) {
- return fn.call(this, args, i18n.gettext, filters.filters);
+ return fn.call(this, args, i18n.gettext, i18n.ngettext, filters.filters);
}
}

0 comments on commit 6e46196

Please sign in to comment.