Skip to content

Instantly share code, notes, and snippets.

@gamefreak
Created March 3, 2012 17:44
Show Gist options
  • Save gamefreak/1967100 to your computer and use it in GitHub Desktop.
Save gamefreak/1967100 to your computer and use it in GitHub Desktop.
function buildHTML(template) {
/*
htmlTemplateChild = string|number|Node|htmlTemplate
htmlTemplate = {
required name: string,
//do not include the 'on' in the event name
optional events: {name: function(event){},...}
optional attrs: {name: string|number, ...},
//attributue shortcuts for frequently use attributes override the coresponding attrs[name] value
optional id: string,
optional class: string|array,
optional href: string
//children and html are mutually exclusive
optional children: htmlTemplateChild|[htmlTemplateChild, ...],
//maps to innerHTML
optional html: string,
}
*/
if (typeof(template) == 'string') {
return document.createTextNode(template);
} else if (typeof(template) == 'number') {
return document.createTextNode(template);
} else if (template instanceof Node) {
return template.cloneNode();
} else {
var element = document.createElement(template.name);
if ('attrs' in template) {
for (var key in template.attrs) {
element.setAttribute(key, template.attrs[key]);
}
}
if ('id' in template) {
element.setAttribute('id', template.id);
}
if ('class' in template) {
if (Array.isArray(template['class'])) {
element.setAttribute('class', template['class'].join(' '));
} else {
element.setAttribute('class', template['class']);
}
}
if ('href' in template) {
element.setAttribute('href', template.href);
}
if ('html' in template) {
element.innerHTML = template.html;
} else if ('children' in template) {
if (Array.isArray(template.children)) {
for (var i = 0; i < template.children.length; i++) {
element.appendChild(buildHTML(template.children[i]));
}
} else {
element.appendChild(buildHTML(template.children));
}
}
if ('events' in template) {
for (var name in template.events) {
element.addEventListener(name, template.events[name]);
}
}
return element;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment