版權聲明:此文首發於個人我的站 Keyon Y,轉載請註明出處。
pug是一個很簡潔很靈活的模板引擎。配合express使用時,在啓動文件(app.js)中配製javascript
// 設置模板類型 app.set('view engine', 'pug'); // 設置模板文件路徑 app.set('views', path.resolve(__dirname, 'src/Views'));
便可使用。css
extends 和 block 實現了pug的繼承。
把html中公共/重複的部分提出,寫在 如layout.pug中,html
// Shared/layout.pug doctype html html head meta(charset="UTF-8") title #{title} meta(name="keywords" content=keywords) meta(name="description" content=description) meta(http-equiv="X-UA-Compatible" content="IE=edge,chrome=1") meta(name="renderer" content="webkit") link(rel='stylesheet' href='/Contents/base.css') //- 公用樣式 block links script(type='text/javascript', src='/assets/jquery-1.10.2.min.js') body include header block content include footer include ../Include/toplink block scripts script(type='text/javascript', src='/Scripts/base.js') //- 公用js block javascript
// Home/index.pug extends ../Shared/layout block links link(rel='stylesheet' href='/Contents/index.css') block scripts script(type='text/javascript', src='/Scripts/index.js') block content include ../Include/homeInclude .container .clear
pug經過mixin即可以實現對html的函數式編程vue
//- include/homeInclude.pug mixin homeBtnBox(num) //- num: 0-報名中 1-已結束 .hr_btnBox a(href="/User" + targetId + "/Mas" class=num == 0 ? "active" : "") 報名中 a(href="/User" + targetId + "/Mas/Require/Finish" class=num == 1 ? "active" : "") 已結束 //- home/home.pug include ../include/homeInclude //- 引入編寫mixin的pug文件 +homeBtnBox(1) //- 傳參調用
.btn(class={"btn_t1": item.status == 0, "btn_t2": item.status == 1, "btn_t3": item.status == 2})
有木有很眼熟?用過ng,vue的同窗都熟悉這種方式,在pug中也能夠這樣使用,可是只有class的屬性能夠使用這種判斷方式,其餘的屬性, href、title、value等等 都不能夠這麼用。java
有時候從後端返回的數據須要進行處理,才能夠使用,能夠在node中間層裏編寫數據處理的方法,運算後再返回,或者 也能夠試試以下的方法:
pug的經過一個 - 表示一段不輸出的代碼,提供一個js語法執行環境,運算js後再將運算結果綁定到pug模板中。node
//- 時間格式化: 最長3個月前 mixin dateFormat(string) - var res = ''; var time_zone = new Date().getTime() - new Date(string.replace('T', ' ')).getTime(); if(time_zone < 0) { res= '<b>1</b>分鐘前' }else if(time_zone < 1 * 60 * 60 * 1000) { res= '<b>' + Math.floor(time_zone / (1000 * 60)) + '</b> 分鐘前'; }else if(time_zone < 1 * 24 * 60 * 60 * 1000){ res= '<b>' + Math.floor(time_zone / (1000 * 60 * 60)) + '</b> 小時前'; }else if(time_zone < 1 * 30 * 24 * 60 * 60 * 1000) { res= '<b>' + Math.floor(time_zone / (24 * 60 * 60 * 1000)) + '</b> 天前'; }else if(time_zone < 3 * 30 * 24 * 60 * 60 * 1000) { res= '<b>' + Math.floor(time_zone / (30 * 24 * 60 * 60 * 1000)) + '</b> 月前'; }else { res= '<b>' + string.slice(0, 10) + '</b>'; } span!= res //- !=綁定一段不轉義的代碼
分享一下pug的中文文檔:https://pug.bootcss.com/language/attributes.htmljquery
歡迎繼續關注本系列博文的其餘精彩文章
Node中間層實踐(一)——基於NodeJS的全棧式開發
Node中間層實踐(二)——搭建項目框架
Node中間層實踐(三)——webpack配置
Node中間層實踐(四)——模板引擎pug
Node中間層實踐(五)——express-中間層的邏輯處理webpack