diff options
| author | Michael Williamson <mike@zwobble.org> | 2014-03-25 12:40:28 +0000 |
|---|---|---|
| committer | Michael Williamson <mike@zwobble.org> | 2014-03-25 12:40:28 +0000 |
| commit | f559596a8bb78306e596734bc44057656b6a2214 (patch) | |
| tree | 74264e152b3f5ba60e1a28b95da6a286bea78209 /lib/html-writer.js | |
| parent | 714f06a92bccb4118072789558cb29c450ac1baf (diff) | |
Split out HTML writer from HTML generator
Diffstat (limited to 'lib/html-writer.js')
| -rw-r--r-- | lib/html-writer.js | 58 |
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, '&') + .replace(/"/g, '"') + .replace(/</g, '<') + .replace(/>/g, '>'); +} |
