Skip to content

Instantly share code, notes, and snippets.

@drew-y
Created April 17, 2016 21:26
Show Gist options
  • Save drew-y/a8a1cc9ea2642d9369e6bb7c70016e8f to your computer and use it in GitHub Desktop.
Save drew-y/a8a1cc9ea2642d9369e6bb7c70016e8f to your computer and use it in GitHub Desktop.
HyperScript for client side templating
var compileAtts = function(atts, node) {
for (var prop in atts) {
var att = document.createAttribute(prop);
att.value = atts[prop].toString();
node.setAttributeNode(att);
}
};
var compileElement = function(tagName, args) {
var atts = args[0] instanceof Object ? args.shift() : false;
var el = document.createElement(tagName);
args.forEach(function(arg) {
if (arg instanceof Node) {
el.appendChild(arg);
} else {
el.innerHTML += arg;
}
});
if (atts) compileAtts(atts, el);
return el;
};
// Elements from https://developer.mozilla.org/en-US/docs/Web/HTML/Element
var tags = ['html', 'base', 'head', 'style', 'title', 'address', 'article',
'footer', 'header', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup', 'nav',
'section', 'dd', 'div', 'dl', 'dt', 'figcaption', 'figure', 'hr', 'li', 'main',
'ol', 'p', 'pre', 'ul', 'a', 'abbr', 'b', 'bdi', 'bdo', 'cite', 'code',
'data', 'dfn', 'em', 'i', 'kbd', 'mark', 'q', 'rp', 'rt', 'rtc', 'ruby', 's',
'samp', 'small', 'span', 'strong', 'sub', 'sup', 'time', 'u', 'var', 'wbr',
'audio', 'map', 'video', 'embed', 'object', 'canvas', 'noscript', 'script',
'del', 'ins', 'caption', 'colgroup', 'table', 'tbody', 'td', 'tfoot', 'th',
'thead', 'tr', 'button', 'datalist', 'fieldset', 'form', 'label', 'legend',
'meter', 'optgroup', 'option', 'output', 'progress', 'select', 'textarea',
'details', 'dialog', 'menu', 'menuitem', 'summary', 'shadow', 'template',
'body', 'link', 'track', 'param', 'area', 'command', 'col', 'base', 'meta',
'hr', 'source', 'img', 'keygen', 'br', 'wbr', 'input'];
// Usage: h('tagName', [attributes = {}], [...innerHTML/Node], [isEmpty = true]);
function h() {
var args = Array.prototype.slice.call(arguments);
var tagName = args.shift();
var isEmpty;
if (args.length >= 1 && typeof args[args.length - 1] === "boolean") {
isEmpty = args.pop();
} else {
isEmpty = emptyTags.indexOf(tagName) !== -1;
}
return compileElement(tagName, args, isEmpty);
}
// Usage h.div(Node || innerHTML)
tags.forEach(function(tagName) {
h[tagName] = function() {
var args = Array.prototype.slice.call(arguments);
return compileElement(tagName, args);
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment