1. 程式人生 > >模板引擎ejs詳解

模板引擎ejs詳解

views data json class ren else file name clu

singsingasong.js:

const ejs=require(‘ejs‘);

ejs.renderFile(‘./views/singsingasong.ejs‘, {‘name‘:‘singsingasong‘,json: {arr: [
  {user: ‘blue‘, pass: ‘123456‘},
  {user: ‘zhangsan‘, pass: ‘654321‘},
  {user: ‘xiaoming‘, pass: ‘999999‘},
]}}, function (err, data){
  console.log(data);
});

singsingasong.ejs :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> -->
    <title>zhagnwen‘s ejs-測試</title>
</head>
<body>
    <div>
        <%= name %>
        <%= json.arr[0].user%>
        <%= json.arr[0].pass%>
        <%= 13 %> + <%= 4 %>

        <!-- 等號 是轉意輸出,減號 不轉意輸出 -->
        <% var str="<div class=‘div1’></div>" %>
        <%-str %>
        <!-- 引用 a.txt文件 -->
        <% include ../a.txt %>

        <%for(var i=0;i<5;i++){%>
            <% include ../a.txt %>      //引入外部文件時註意層級‘../’
            <% } %>
        }
    </div>
</body>
</html>

知識點:

如果用到include,必須把它單獨標記出來.因為它是ejs自帶的,不是js的:

<% if(type==‘admin‘){ %>
<% include ../style/admin.css %>
<%}else{%>
<% include ../style/user.css %>
<% } %>

模板引擎ejs詳解