Embedded JavaScript templates
后台模板引擎
var ejs = require("ejs");
//模板
var string = "哈哈哈哈哈第<%= a %>个";
//数据
var data = {
a : 6
};
//数据绑定
var html = ejs.render(string, data);
//输出模板数据
console.log(html);
使用在html也页中:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>哈哈哈第<%= a %>个</h1>
<ul>
<% for(var i = 0; i < news.length; i++){ %>
<li><%= news[i] %></li>
<%}%>
</ul>
</body>
</html>
var ejs = require("ejs");
var fs = require("fs");
var http = require("http");
http.createServer(function (req, res) {
fs.readFile("./views/index.ejs", function (err, data) {
var template = data.toString();
var dictionary = {
a : 6,
news : ["行吧", "说的", "很牛逼"]
};
var html = ejs.render(template, dictionary);
res.writeHead(200, {'content-type': 'text/html; charset=utf-8'});
res.end(html);
});
}).listen(81, "127.0.0.1");
效果图: