A quick and dirty markup generator in JavaScript
Here’s a quick and dirty XML/HTML generator. Without even bothering to write a new class, I simply extend an Array instance with a few helpers that can be chained.
The generator:
function xmlEscape(s) {
return s.replace(/[<>&"]/g, function (c) {
return "&"
+ { "<": "lt", ">": "gt", "&": "amp", "\"": "quot" }[c]
+ ";";
});
}
var xml = [ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" ];
xml.text = function () {
Array.prototype.push.apply(this, arguments);
return this;
};
xml.elem = function (tagName, attrs, selfClose) {
this.text("<", tagName);
for (var a in attrs || {}) {
this.text(" ", a, "=\"", xmlEscape(String(attrs[a])), "\"");
}
this.text(selfClose ? "/" : "", ">\n");
return this;
};
xml.toString = function () { return this.join(""); }
Usage examples:
// Add an element with attributes
xml.elem("root", { attrib1: "hello", attrib2: "world" });
// Add a self-closing element (as child of previous)
xml.elem("child", { attrib: 42 }, true);
// Add some nested children
// Note that calls to elem() and text() can be chained
xml.elem("child")
.elem("nested", {}, true)
.elem("/child");
// Add an element with text content
xml.elem("child")
.text("Hello World!")
.elem("/child");
// Close the root node
xml.elem("/root");
// Get the generated XML
alert(xml);
Note: I simply did this because using one of the existing HTML template libraries out there would be an overkill for the task at hand.