ejs是一個js的模板引擎,基本的思路就是后台js提供數據,前端通過<%%>標簽解析出來:
比如我們建立一個ejs文件:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <!--這里的a和news都是后台ejs渲染給的--> <div>iphone<%=a%></div> <ul> <% for(var i = 0;i<news.length;i++){%> <li><%=news[i]%></li> <%} %> </ul> </body> </html>
然后我們有一個ejs_test.js文件提供數據渲染:
var ejs = require("ejs"); var fs = require("fs"); fs.readFile("./ejs_test.ejs",function (err,data) { var template = data.toString(); var dictionary = {a:66,news:["java","javascript","c"]}; var html = ejs.render(template,dictionary);//用dictionary數據源填充template console.log(html); })
這里我們在控制台輸出渲染完成后的內容: