Saturday, May 16, 2015

HTML up and down

I just found a html to json parser, himalaya, and i though this needs a json to html parser.

var mariana = {
parse : function(json){
return mariana.checkFragment(json);
},
checkFragment : function(arr){
var out = '';
for(fragment of arr){
switch(fragment.kind){
case "element": out += mariana.element(fragment); break;
case "text": out += fragment.content; break;
case "comment": out += '<!--'+fragment.content+'-->'; break;
}
}
return out;
},
element : function(obj){
var out = '<'+obj.tagName+mariana.attributes(obj)+'>';
var voidTags = [
"!doctype", "area", "base", "br", "col", "command",
"embed", "hr", "img", "input", "keygen", "link",
"meta", "param", "source", "track", "wbr"];
if(voidTags.indexOf(obj.tagName) === -1){
if(typeof obj.children !== 'undefined'){
out += mariana.checkFragment(obj.children);
}
out += '</'+obj.tagName+'>';
}
return out;
},
attributes : function(obj){
var out = [];
if(typeof obj.id !== 'undefined'){
out[out.length] = 'id="'+obj.id+'"';
}
if(typeof obj.className !== 'undefined'){
out[out.length] = 'class="'+obj.className.join(' ')+'"';
}
if(typeof obj.dataset !== 'undefined'){
for(key in obj.dataset){
out[out.length] = 'data-'+key+'="'+obj.dataset[key]+'"';
}
}
var excluded = ['id', 'tagName', 'className', 'dataset', 'children', 'kind'];
for(key in obj){
if(excluded.indexOf(key) == -1){
out[out.length] = key+'="'+obj[key]+'"';
}
}
return out.length !== 0 ? ' '+out.join(' ') : '';
}
};
view raw mariana.js hosted with ❤ by GitHub

It isn't fancy, but it gets the work done and it's readable.

No comments: