前言
以前在撰寫 HTML 檔時是不是每支檔案都必須要有 !DOCTYPE html、head、header、footer 等標籤,而當網站頁數一多起來,在維護上就變得不容易了。
最簡單的例子就是當 header 有變更時,所有頁面的 header 必須修正,這就得一頁一頁的修改,效率極為慘烈。
於是 template 模版語言就是因此而被開發出來,不僅能夠讓所有頁面共用同一份 layout ,還能使用 迴圈、判定參數、傳入資料等行為,將開發效率提升了一個檔次,其實很多前端開發者到後來都不再寫 HTML 了,而轉成寫 ejs、pug等模版語言,只需要搭配編譯工具轉成 HTML 即可達到 具有簡潔的架構、易維護 的成效。
安裝套件
我們使用的是 ejs-locals 的套件,以下附上官方 github 及 npm 連結
ejs-locals github
ejs-locals npm
在專案內輸入
1 | npm install ejs-locals --save |
Express 設定
在 app.js 中加入以下引入設定
1 | const express = require('express'); |
template 建立
來到根目錄,建立 views 資料夾,名稱可以隨便取,但必須跟上方 ./views 一樣才行呦。
在底下建立 layout.ejs、index.ejs、header.ejs
- layout.ejs 內容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<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><%= documentTitle %></title>
</head>
<body>
<header>
<% include header %>
</header>
<%- body %>
<footer>
<% include header %>
</footer>
</body>
</html> - index.ejs 內容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18<% layout('layout') %>
<h1>Index</h1>
<% if (show) { %>
<span>顯示資料: show = true</span>
<% } else { %>
<span>不顯示資料: show = false</span>
<% } %>
<%- title %>
<h1>主辦人: <%= boss %></h1>
<ul>
<% for(i = 0;i < course.length; i++) { %>
<li><%= course[i] %></li>
<% } %>
</ul> - header.ejs 內容輸出及引入 template 的方法:
1
<p>I'm in the header.</p>
<% layout('layout') %>: 找到layout.ejs並搭配layout.ejs中的<%- body %>渲染內容<% include header %>: 找到header.ejs並搭配HTML渲染內容
此範例中有寫入 if、for迴圈 的方法,其實跟寫 JavaScript 很雷同,差在要顯示時需要加入 ejs 的引入寫法而已
在 ejs 內顯示傳入參數的方法:
<%= 傳入參數的屬性 %>: 此方法會將傳入資料以字串形式渲染出來<%- 傳入參數的屬性 %>: 此方法會將傳入資料以HTML形式渲染出來