dt-parser
Version:
Δt html parser - async & dynamic templating engine
76 lines (60 loc) • 2.1 kB
JavaScript
(function() {
var Parser, Template, XMLParser, parse,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
XMLParser = require('htmlparser2').WritableStream;
Template = require('dynamictemplate').Template;
Parser = (function() {
function Parser(stream, opts) {
var pause, resume;
if (opts == null) {
opts = {};
}
this.onend = __bind(this.onend, this);
this.onerror = __bind(this.onerror, this);
this.onclosetag = __bind(this.onclosetag, this);
this.onattribute = __bind(this.onattribute, this);
this.ontext = __bind(this.ontext, this);
this.onopentagname = __bind(this.onopentagname, this);
opts.end = false;
pause = stream.pause.bind(stream);
resume = stream.resume.bind(stream);
pause();
this.tpl = new Template(opts, resume);
this.parser = new XMLParser(this, opts.parser);
this.tpl.on('resume', resume);
this.tpl.on('pause', pause);
stream.pipe(this.parser);
this.parents = [];
this.el = this.tpl.xml;
}
Parser.prototype.onopentagname = function(name) {
this.parents.unshift(this.el);
return this.el = this.parents[0].tag(name);
};
Parser.prototype.ontext = function(text) {
var _base;
return typeof (_base = this.el).text === "function" ? _base.text(text) : void 0;
};
Parser.prototype.onattribute = function(key, value) {
var _base;
return typeof (_base = this.el).attr === "function" ? _base.attr(key, value) : void 0;
};
Parser.prototype.onclosetag = function(name) {
this.el.end();
return this.el = this.parents.shift();
};
Parser.prototype.onerror = function(err) {
return this.tpl.emit('error', err);
};
Parser.prototype.onend = function() {
this.tpl.end();
return this.tpl = this.el = this.parents = null;
};
return Parser;
})();
parse = function(stream, opts) {
return new Parser(stream, opts).tpl;
};
parse.Parser = Parser;
module.exports = parse;
}).call(this);