模板引擎:ejs

本文共--字 阅读约--分钟 | 浏览: -- Last Updated: 2021-07-03

ejs:温和式、非侵入式、弱依赖的模板语言。

安装:npm install ejs

使用:

1、使用<%= name %>来替换变量。

const ejs = require('ejs');

ejs.renderFile('./demo.ejs', {name: 'jack'}, function (err, data) {
  console.log(data);
})
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div>
    我的名字是:<%= name %>
  </div>
</body>
</html>

2、使用for循环

ejs.renderFile('./demo.ejs', {
  json: {
    arr: [
      { user: 'jack'},
      { user: '小明'}
    ]
  }
}, function (err, data) {
  console.log(data);
})
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <% for(var i =0; i< json.arr.length; i++) { %>
    <div>用户名:<%= json.arr[i].user %></div>
  <% } %>
</body>
</html>

3、使用<%- name %>非转义输出,注意是-而不再是=

const ejs = require('ejs');

ejs.renderFile('./demo3.ejs', {
  str: '<div></div>'
} ,function (err, data) {
  console.log(data);
})
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <%- str %>
</body>
</html>

4、使用<% include ./demo.txt %>,引入外部文件,会将文件内容渲染到模板中,可以搭配for来循环引入。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <% include ./demo.txt %>
  <% for(var i = 0; i < 2; i++ ) { %>
    <% include ./demo.txt %>
  <% } %>
</body>
</html>

5、使用if、else

根据不同的数据引入不同的css文件


ejs.renderFile('./demo.ejs', {type: 'module1'} ,function (err, data) {
  console.log(data);
})
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    <% if(type == 'module1') { %>
    <%  include ./style/module1.css %>
    <% } else { %>
    <%  include ./style/module2.css %>
    <% } %>
  </style>
</head>
<body>
  <div>hello</div>
</body>
</html>