nging
Version:
Template engine based on jml.
81 lines (61 loc) • 1.67 kB
JavaScript
var util = require("util");
function checkType(object, typeName) {
return toString.apply(object)=="[object "+typeName+"]";
}
function tag(component, props, isTail) {
var pstr = "";
for (key in props) {
pstr += " "+key+"=\""+props[key]+"\"";
}
return "<"+(isTail?"/":"")+String(component)+pstr+">";
}
function addTabForEachLine(text) {
return text.split("\n").map(function(line) {
return " "+line;
}).join("\n");
}
function render(jml) {
if (checkType(jml,'String')) {
return jml;
};
var component = jml[0];
var props, nodes;
if (jml.length>1 && checkType(jml[1], 'Object')) {
props = jml[1];
nodes = jml.slice(2);
} else {
props = {};
nodes = jml.slice(1) || [];
}
if (!checkType(component,'String')) {
var c = new component();
// c.init(props, nodes);
c.props = props?props:{};
c.props.nodes = nodes;
return render(c.jml());
};
var html="";
for (key in nodes) {
if (nodes.length>1) {
html+="\n"+addTabForEachLine(render(nodes[key]));
} else {
html+= render(nodes[key]);
}
}
html+=nodes.length>1?"\n":"";
return tag(component,props)+html+tag(component,{},true);
}
// function Component() {
// this.props = {};
// this.props.nodes = [];
// }
// function create(json) {
// var NewComponent = {};
// util.inherits(NewComponent, Component);
// NewComponent.prototype.jml = json.jml;
// return NewComponent;
// }
var nging = {};
nging.render = render;
//engen.create = create;
module.exports = nging;