Created
October 9, 2015 02:13
-
-
Save twfarland/5f77895deaf87ca8ef57 to your computer and use it in GitHub Desktop.
generate html strings from js with same syntax as https://gist.github.com/twfarland/fdcbd933bd876af79b33
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const voidElements = { area:1, base:1, br:1, col:1, command:1, embed:1, hr:1, img:1, input:1, keygen:1, link:1, meta:1, param:1, source:1, track:1, wbr:1 }; | |
function exists (n) { | |
if (n instanceof Array || typeof n === 'string') return n.length > 0; | |
return !!(n === 0 || n); | |
} | |
function flatten (obj) { | |
var res = []; | |
var i; | |
for (i = 0; i < obj.length; i++) { | |
if (exists(obj[i])) { | |
if (obj[i] instanceof Array) { | |
res = res.concat(flatten(obj[i])); | |
} else { | |
res.push(obj[i]); | |
} | |
} | |
} | |
return res; | |
} | |
function ElHead (head, attrs) { | |
const parts = head.split(/\s+/); | |
var _attrs = {}; | |
var a ; | |
var attrStr = ''; | |
var tag = 'div'; | |
var i; | |
var p; | |
var c; | |
if (attrs) { | |
for (a in attrs) { | |
_attrs[a] = attrs[a]; } | |
} | |
for (i = 0; i < parts.length; i++) { | |
p = parts[i]; | |
c = p.charAt(0); | |
if (c === '#') { | |
_attrs.id = p.slice(1); | |
} else if (c === '.') { | |
_attrs['class'] = (!_attrs['class']) ? p.slice(1) : _attrs['class'] + ' ' + p.slice(1); | |
} else { | |
tag = p; | |
} | |
} | |
for (a in _attrs) { | |
attrStr += ' ' + a + '="' + _attrs[a] + '"'; | |
} | |
return [tag, attrStr]; | |
} | |
function El (head, attrs, ... children) { | |
children = children && flatten(children); | |
const [tag, attrStr] = ElHead(head, attrs); | |
var res = '<' + tag + attrStr + '>'; | |
var c; | |
if (!voidElements[tag] && children) { | |
for (c = 0; c < children.length; c++) { | |
res += children[c]; | |
} | |
res += '</' + tag + '>'; | |
} | |
return res; | |
} | |
export default El; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment