模板引擎ejs
1、网站
2、app.js
var http=require("http"); var ejs = require('ejs'); var path = require('path'); http.createServer(function(req, res){ if (req.url === '/index') { res.writeHead(200,{ "content-type":"text/html;charset=utf-8" }) var people = ['geddy', 'neil', 'alex']; var html = ejs.render('<h2 style="color:red"><%= people.join(", "); %></h2>', {people: people}); res.write(html); res.end() } if (req.url === '/detail') { res.writeHead(200,{ "content-type":"text/html;charset=utf-8" }) var book = {id: 1, name: '小明', price: 10.00}; ejs.renderFile(path.join(__dirname, 'pages', 'detail.html'), {book: book}, function(err, str) { res.write(str); res.end() }); }
if (req.url === '/list') {
res.writeHead(200,{
"content-type":"text/html;charset=utf-8"
})
// 注意 bookList 的格式 "id" "name"的双引号不能省
var bookList = [{"id": 1, "name": "java编程思想", "price": 10.00},{"id": 2, "name": "springboot", "price": 20.00}];
ejs.renderFile(path.join(__dirname, 'pages', 'list.html'), {bookList: bookList}, function(err, str) {
res.write(str);
res.end()
});
} }).listen('3000', function() { console.log('服务器已经启动,请访问http://127.0.0.1:3000/'); });
pages/detail.html
<!DOCTYPE html> <html> <head> <title>detail页面</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="/static/css/common.css"> </head> <body> <h2>detail页面</h2> <form method="post" action="/edit"> <input type="hidden" name="id" value="<%= book.id %>"> 书名:<input type="text" name="name" value="<%= book.name %>"><br/> 价格:<input type="text" name="price" value="<%= book.price %>"><br/> <input type="submit" value="修改"> </form> </body> </html>
pages/list.html
<!DOCTYPE html> <html> <head> <title>list页面</title> <meta charset="utf-8"> </head> <body> <h2>list页面</h2> <ul> <% for(var i = 0; i < bookList.length; i++) { %> <li><%= bookList[i].name %></li> <% } %> </ul> </body> </html>
posted on 2019-07-09 19:45 wenbin_ouyang 阅读(165) 评论(0) 编辑 收藏 举报