From f559596a8bb78306e596734bc44057656b6a2214 Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Tue, 25 Mar 2014 12:40:28 +0000 Subject: Split out HTML writer from HTML generator --- lib/html-writer.js | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 lib/html-writer.js (limited to 'lib/html-writer.js') diff --git a/lib/html-writer.js b/lib/html-writer.js new file mode 100644 index 0000000..d2fb67b --- /dev/null +++ b/lib/html-writer.js @@ -0,0 +1,58 @@ +var util = require("util"); +var _ = require("underscore"); + +exports.writer = writer; + +function writer() { + var fragments = []; + + function open(tagName, attributes) { + var attributeString = generateAttributeString(attributes) + fragments.push(util.format("<%s%s>", tagName, attributeString)); + } + + function close(tagName) { + fragments.push(util.format("", tagName)); + } + + function selfClosing(tagName, attributes) { + var attributeString = generateAttributeString(attributes) + fragments.push(util.format("<%s%s />", tagName, attributeString)); + } + + function generateAttributeString(attributes) { + return _.map(attributes, function(value, key) { + return util.format(' %s="%s"', key, escapeHtml(value)); + }).join(""); + } + + function text(value) { + fragments.push(escapeHtml(value)) + } + + function append(html) { + fragments.push(html); + } + + function asString() { + return fragments.join(""); + } + + return { + asString: asString, + open: open, + close: close, + text: text, + selfClosing: selfClosing, + append: append + }; +} + + +function escapeHtml(value) { + return value + .replace(/&/g, '&') + .replace(/"/g, '"') + .replace(//g, '>'); +} -- cgit v1.2.3