雜項 ----模板引擎(補充)
template是一個模板引擎
使用:
1.簡單使用
// 匯入模板引擎模組
const template = require('art-template');
// 將特定模板與特定資料進行拼接
1 const html = template('./views/index.art',{ 2 data: { 3 name: '張三', 4 age: 20 5 } 6 }); 7 8 index.art:↓ 9 <div> 10 <span>{{data.name}}</span> 11<span>{{data.age}}</span> 12 </div>
2.語法
art-template同時支援兩種模板語法:標準語法和原始語法。
標準語法可以讓模板更容易讀寫,原始語法具有強大的邏輯處理能力。
標準語法: {{ 資料 }}
原始語法:<%=資料 %>
1.輸出:
標準語法:{{ 資料 }} 原始語法:<%=資料 %> <!-- 標準語法 --> <h2>{{value}}</h2> <h2>{{a ? b : c}}</h2> <h2>{{a + b}}</h2> <!-- 原始語法 --> <h2><%= value %></h2> <h2><%= a ? b : c %></h2> <h2><%= a + b %></h2>
2.原文輸出
標準語法:{{@ 資料 }} 原始語法:<%-資料 %> 如果資料中攜帶HTML標籤,預設模板引擎不會解析標籤,會將其轉義後輸出。(直接輸出標籤) <!-- 標準語法 --> <h2>{{@ value }}</h2> <!-- 原始語法 --> <h2><%- value %></h2>
3.條件判斷
<!-- 標準語法 --> {{if 條件}} ... {{/if}} {{if v1}} ... {{else if v2}} ... {{/if}} <!-- 原始語法 --> <% if (value) { %> ... <% } %> <% if (v1) { %> ... <% } else if (v2) { %> ... <% } %>
4.迴圈
標準語法:{{each 資料}} {{/each}} 原始語法:<% for() { %> <% } %> <!-- 標準語法 --> {{each target}} {{$index}} {{$value}} {{/each}} <!-- 原始語法 --> <% for(var i = 0; i < target.length; i++){ %> <%= i %> <%= target[i] %> <% } %>
5.子模版
使用子模板可以將網站公共區塊(頭部、底部)抽離到單獨的檔案中。 標準語法:{{include '模板'}} 原始語法:<%include('模板') %> <!-- 標準語法 --> {{include './header.art'}} <!-- 原始語法 --> <% include('./header.art') %>
6.模板繼承示例
//繼承的模板和挖坑的地方 <!doctype html> <html> <head> <meta charset="utf-8"> <title>HTML骨架模板</title> {{block 'head'}}{{/block}} </head> <body> {{block 'content'}}{{/block}} </body> </html>
//使用模板的示例 <!--index.art 首頁模板--> {{extend './layout.art'}} {{block 'head'}} <link rel="stylesheet" href="custom.css"> {{/block}} {{block 'content'}} <p>This is just an awesome page.</p> {{/block}}
3.模板配置
向模板中匯入變數 template.defaults.imports.變數名 = 變數值;
設定模板根目錄 template.defaults.root = 模板目錄
設定模板預設字尾 template.defaults.extname = '.art'
也可以這樣:在使用前更改預設字尾,目錄可能也可以
template.defaults.extname = '.art' const html1 = template('01',{}) console.log(html1) template.defaults.extname = '.html' const html2 = template('02',{}) console.log(html2)
第三方模組 router
功能:實現路由
使用步驟:
獲取路由物件
呼叫路由物件提供的方法建立路由
啟用路由,使路由生效
const getRouter = require('router') const router = getRouter(); router.get('/add', (req, res) => { res.end('Hello World!') }) server.on('request', (req, res) => { router(req, res) })
--------------------PS--------------------------------------------
如果想從 xx.post('/add',(res,req)=>{})中獲得資料,需要第三方模組 body-parser
第三方模組 serve-static
功能:實現靜態資源訪問服務
步驟:
引入serve-static模組獲取建立靜態資源服務功能的方法
呼叫方法建立靜態資源服務並指定靜態資源服務目錄
啟用靜態資源服務功能
const serveStatic = require('serve-static') const serve = serveStatic('public') server.on('request', () => { serve(req, res) }) server.listen(3000)