ejs模板引擎

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);
})

  这里我们在控制台输出渲染完成后的内容:

原文地址:https://www.cnblogs.com/yk123/p/7171705.html