日期:2014-05-16  浏览次数:20342 次

做着玩的NodeJS服务器端模板引擎--Elf

基本功能能用,但是很多地方还比较简陋

?

服务器端使用方法:

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>
?

?

?

在<?JS................?>中支持一般的javascript服务器端编程。

支持表达式语言${}

?

在浏览器键入http://localhost:3000

?

显示结果

?

?

User List
John 123 24
Jack 124 21
Jane 125 23