tumble/lib/parser.js

175 lines
3.9 KiB
JavaScript

// Generated by CoffeeScript 1.6.1
(function() {
var Contexter, _;
_ = require('underscore');
Contexter = (function() {
function Contexter(content) {
this.content = content;
this.stack = [this.content];
this.templates = {};
this.depth = 0;
}
Contexter.prototype.has_any = function(name) {
return _.find(this.stack, function(o) {
return _.has(o, name);
});
};
Contexter.prototype.has_any_one = function(name) {
var p;
p = this.has_any(name);
if (p) {
return p[name];
} else {
return null;
}
};
Contexter.prototype.has = function(name) {
if (this.stack[0][name] != null) {
return this.stack[0][name];
} else {
return null;
}
};
Contexter.prototype.get = function(name, alt) {
var p;
if (alt == null) {
alt = '';
}
p = this.has_any_one(name);
if (p && (_.isString(p) || _.isNumber(p))) {
return p;
}
return this.render(name);
};
Contexter.prototype.once = function(obj, cb) {
var r;
this.stack.unshift(obj);
this.depth++;
if (this.depth > 10) {
throw new Error('recursion-error');
}
r = cb(this);
this.stack.shift();
this.depth--;
return r;
};
Contexter.prototype.when = function(name, cb) {
var p;
p = this.has_any_one(name);
if (p) {
return cb(this);
} else {
return '';
}
};
Contexter.prototype["if"] = function(name, cb) {
var p;
p = this.has(name);
if (p) {
return cb(this);
} else {
return '';
}
};
Contexter.prototype.block = function(name, cb) {
var p;
p = this.has_any_one(name);
if (p && _.isObject(p)) {
return this.once(p, cb);
} else {
return '';
}
};
Contexter.prototype.many = function(name, cb) {
var ps,
_this = this;
ps = this.has(name);
if (!(ps && _.isArray(ps))) {
return "";
}
return (_.map(ps, function(p) {
return _this.once(p, cb);
})).join('');
};
Contexter.prototype.template = function(name, cb) {
this.templates[name] = cb;
return "";
};
Contexter.prototype.render = function(name) {
var ret;
if ((this.templates[name] != null) && _.isFunction(this.templates[name])) {
this.depth++;
if (this.depth > 10) {
throw new Error('recursion-error');
}
ret = this.templates[name](this);
this.depth--;
return ret;
} else {
return "";
}
};
return Contexter;
})();
module.exports = function(ast, data) {
var cmd, context, o;
context = new Contexter(data);
cmd = function(o) {
switch (o.unit) {
case 'variable':
return function(context) {
return context.get(o.name);
};
case 'text':
return function(context) {
return o.content;
};
case 'block':
return function(context) {
return context[o.type](o.name, function(context) {
var p;
return ((function() {
var _i, _len, _ref, _results;
_ref = o.content;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
p = _ref[_i];
_results.push(cmd(p)(context));
}
return _results;
})()).join("");
});
};
}
};
return ((function() {
var _i, _len, _ref, _results;
_ref = ast.content;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
o = _ref[_i];
_results.push(cmd(o)(context));
}
return _results;
})()).join("");
};
}).call(this);