官方API:
https://www.npmjs.com/package/ejs - 模板引擎
ejs文件(和普通html文件没什么区别,只是多增加了变量)
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <meta http-equiv="X-UA-Compatible" content="ie=edge">
7 <title>Document</title>
8 </head>
9 <body>
10 <h1>蹦叉叉<%= a%></h1>
11 <ul>
12 <%
13 for(let i = 0 ; i<obj.length ;i++){
14 if(obj[i].name=='lisi'){
15 %>
16 <li><%= obj[i].name %></li>
17 <%
18 }
19 }
20 %>
21 </ul>
22 </body>
23 </html>
node-ejsEngine.js
1 // ejs 和 jade 2 const ejs = require('ejs'); 3 const fs = require('fs'); 4 const http = require('http'); 5 6 7 let server = http.createServer(function (req, res) { 8 fs.readFile('./view/index.ejs', function (err, data) { 9 10 let template = data.toString(); 11 let dictionary = { 12 a: 6, 13 arr: [ 14 1, 2, 3, 4, 5 15 ], 16 obj: [ 17 { 18 'name': 'zhangsan' 19 }, 20 { 21 'name': 'lisi' 22 }, 23 { 24 'name': 'liwu' 25 } 26 ] 27 } 28 29 let html = ejs.render(template, dictionary); 30 res.writeHead(200, { 31 'Content-type': 'text/html;charset=UTF-8' 32 }) 33 res.end(html) 34 }) 35 36 }) 37 38 server.listen(80, '127.0.0.1')