本人刚接触node3天。想想node不提供类似于asp,php,jsp这样的动态页技术。jade模板语法又不喜欢,所以就做了一个自己的模板引擎。比较简陋。但好歹能支持最基本的功能
服务器端使用方法:
var Engine = require("./elf").Engine;
var http = require("http");
// 将模板位置传入引擎
var engine = new Engine({
"test": "./table.html"
});
var server = http.createServer(function(req, res) {
// 得到相应时,从modal这里得到的结果集
var param = {
tableName: "User List",
userList: [
{name: "John", password: "123", age: 24},
{name: "Jack", password: "124", age: 21},
{name: "Jane", password: "125", age: 23},
{name: "James", password: "126", age: 45},
]
};
res.writeHead(200, {"Content-Type": "text/html"});
// 寻找对应模板
res.write(engine.view("test", param));
res.end();
});
server.listen(3000);
模板页面:table.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
#wrap {
margin: 0 auto;
width: 800px;
}
</style>
</head>
<body>
<div id="wrap">
<?JS var t = '123'; var s = "'";
function convertNull(target) {
return target == null ? "" : target;
}
?>
<div>${tableName}</div>
<div>${t}</div>
<div>${s}</div>
<table>
<?JS
for (var index = 0; index < userList.length; index++) {
if (userList[index].age && userList[index].age > "24") {
continue;
}
?>
<tr>
<td>${userList[index].name}'</td>
<td>${convertNull(userList[index].password)}</td>
<td>${userList[index].age}</td>
</tr>
<?JS}?>
</table>
</div>
</body>
</html>
大概功能为 1.支持<?JS ....?>中一般服务器端js编程,包括定义function等 2.支持表达式语言。