aboutsummaryrefslogtreecommitdiff
path: root/lib/html-writer.js
diff options
context:
space:
mode:
authorMichael Williamson <mike@zwobble.org>2014-03-25 12:40:28 +0000
committerMichael Williamson <mike@zwobble.org>2014-03-25 12:40:28 +0000
commitf559596a8bb78306e596734bc44057656b6a2214 (patch)
tree74264e152b3f5ba60e1a28b95da6a286bea78209 /lib/html-writer.js
parent714f06a92bccb4118072789558cb29c450ac1baf (diff)
Split out HTML writer from HTML generator
Diffstat (limited to 'lib/html-writer.js')
-rw-r--r--lib/html-writer.js58
1 files changed, 58 insertions, 0 deletions
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("</%s>", 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, '&amp;')
+ .replace(/"/g, '&quot;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;');
+}