版权声明:此文首发于个人我的站 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