UNPKG

xtemplate

Version:

eXtensible Template Engine lib on browser and nodejs. support async control, inheritance, include, logic expression, custom function and more.

122 lines (101 loc) 2.61 kB
/** * LinkedBuffer of generate content from xtemplate * @author yiminghe@gmail.com */ var util = require('./util'); function Buffer(list, next) { this.list = list; this.init(); this.next = next; this.ready = false; } Buffer.prototype = { constructor: Buffer, isBuffer: 1, init: function () { this.data = ''; }, append: function (data) { this.data += data; return this; }, write: function (data) { // ignore null or undefined if (data != null) { this.append(data); } return this; }, writeEscaped: function (data) { // ignore null or undefined if (data != null) { this.append(util.escapeHtml(data)); } return this; }, async: function (fn) { var self = this; var list = self.list; var nextFragment = new Buffer(list, self.next); var asyncFragment = new Buffer(list, nextFragment); self.next = asyncFragment; self.ready = true; fn(asyncFragment); return nextFragment; }, error: function (reason) { var callback = this.list.callback; if (callback) { callback(reason, undefined); this.list.callback = null; } }, end: function () { var self = this; if (self.list.callback) { self.ready = true; self.list.flush(); } return self; } }; function LinkedBuffer(callback, config) { var self = this; self.config = config; self.head = new Buffer(self, undefined); self.callback = callback; this.init(); } LinkedBuffer.prototype = { constructor: LinkedBuffer, init: function () { this.data = ''; }, append: function (data) { this.data += data; }, end: function () { this.callback(null, this.data); this.callback = null; }, flush: function () { var self = this; var fragment = self.head; while (fragment) { if (fragment.ready) { this.append(fragment.data); } else { self.head = fragment; return; } fragment = fragment.next; } self.end(); } }; LinkedBuffer.Buffer = Buffer; module.exports = LinkedBuffer; /** * 2014-06-19 yiminghe@gmail.com * string concat is faster than array join: 85ms<-> 131ms */