Created
April 8, 2015 13:26
-
-
Save xurenlu/42e65cf8944ea7567691 to your computer and use it in GitHub Desktop.
json2html.还差HTML解析模板的支持.todo:加上knockoutjs的后续支持.
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
var serverOutput =[ { | |
"tag":"bootpanel", | |
"children": [ | |
{ | |
"tag": "panel", | |
"children": [ | |
{ | |
"tag": "button", | |
"class": ["btn-primary"], | |
"children": "Submit" | |
}, | |
{ | |
"tag": "button", | |
"class": ["btn-success"], | |
"children": "cancel" | |
}, | |
"testing" | |
] | |
} | |
] | |
} | |
]; | |
var render = function (obj) { | |
this._typeOf = function (node) { | |
/** | |
* String Array Object Number | |
*/ | |
return Object.prototype.toString.call(node).split(" ")[1].replace(/]/, ""); | |
} | |
this._init = function (node) { | |
node["class"] = node["class"] || []; | |
return node; | |
}; | |
this._handleChildren = function (node) { | |
node["children"] = node["children"] || []; | |
if (this._typeOf(node["children"]) == "String") { | |
return node["children"]; | |
} | |
var nodes = []; | |
for (var i = 0; i < node["children"].length; i++) { | |
nodes.push(render(node["children"][i])); | |
} | |
return nodes.join(""); | |
}; | |
this.model_bootpanel = function(node){ | |
return ['<div class="jumbotron">', | |
'<h1>Hello, world!</h1>', | |
'<p>'].join("")+ | |
this._handleChildren(node)+'</p> <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>'+ '</div>'; | |
}; | |
if (this._typeOf(obj) == "String") return obj; | |
if (this._typeOf(obj) == "Array"){ | |
var nodes = []; | |
for(var i=0;i<obj.length;i++){ | |
nodes.push(render(obj[i])); | |
} | |
return nodes.join(""); | |
} | |
obj = this._init(obj); | |
if (this["model_" + obj.tag]) { | |
return this["model_" + obj.tag](obj); | |
} else { | |
return "<" + obj.tag + " class='panel panel-default" + | |
obj["class"].join(" ") + " ' > " + this._handleChildren(obj) + "</" + obj.tag + ">" | |
} | |
}; | |
console.log(render(serverOutput)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment