# Node + 樣板引擎
### 樣板引擎
> 將邏輯與內容直接嵌入到HTML頁面上, 優點快速、簡潔
常見樣板引擎有Jade及EJS,EJS常見的像是 **<%=輸出變數%>**,JADE則是利用縮排來定義結構且不需要< , />。
### EJS
安裝ejs
```javascript=
$ npm install ejs --save
$ npm install ejs-locals --save
```
載入ejs-locals
```javascript=
let engine = require('ejs-locals')
```
## 設定樣板引擎:star::star:
設定ejs為樣版引擎以及設定讀取的資料夾為根目錄的**views**資料夾。並且在根目錄建立一個views的資料夾。
```javascript=
app.engine('ejs', engine);
app.set('views', './views');
app.set('view engine', 'ejs');
```
### 建立樣板
在views資料夾中新增index.ejs,建立基礎html標籤
```javascript=
//index.ejs
<body>
<h1>首頁</h1>
</body>
```
修改app.get路由,進入首頁時,畫面會呈現 views中的index.ejs檔案
```javascript=
app.get('/', (req, res) => {
res.render('index')
})
```
### EJS基礎語法
#### <%= 輸出變數 %>
傳送參數
```javascript=
app.get('/', (req,res) => {
res..render('index', {
'title': '首頁'
})
})
```
```javascript=
//index.ejs
<body>
<h1><%= title %></h1>
</body>
```
### <%-輸出變數%>
輸出HTML標籤
```javascript=
app.get('/', (req,res) => {
res.render('index', {
'title': '首頁',
'subtitle': '<h2>副標題</h2>'
})
})
```
```javascript=
//index.ejs
<body>
<h1><%= title %></h1>
<%- subtitle %>
</body>
```
### 在EJS中插入判斷式
```javascript=
res..render('index', {
'title': '首頁',
'subtitle': '<h2>副標題</h2>',
'show': true
})
```
```javascript=
//index.ejs
<h1><%= title %></h1>
<%- subtitle %>
<% if(show) { %>
<p>true</p>
<% } else { %>
<p>false</p>
<% } %>
```
### 陣列<%- %>
```javascript=
<% for (var i=0; i < array.length; i++){ %>
<li><%- array[i] %></li>
<% } %>
```