版权声明:此文首发于我的个人站Keyon Y,转载请注明出处。

pug是一个很简洁很灵活的模板引擎。配合express使用时,在启动文件(app.js)中配制

1
2
3
4
// 设置模板类型
app.set('view engine', 'pug');
// 设置模板文件路径
app.set('views', path.resolve(__dirname, 'src/Views'));

即可使用。

pug的继承

extends 和 block 实现了pug的继承。
把html中公共/重复的部分提出,写在 如layout.pug中,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 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

1
2
3
4
5
6
7
8
9
10
11
12
13
// 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

Mixin—对html进行函数式编程

pug通过mixin便可以实现对html的函数式编程

1
2
3
4
5
6
7
8
9
10
//- 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) //- 传参调用

判断并绑定多个classname的方法

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等等 都不可以这么用。

逻辑运算后再绑定数据的方法

有时候从后端返回的数据需要进行处理,才可以使用,可以在node中间层里编写数据处理的方法,运算后再返回,或者 也可以试试如下的方法:
pug的通过一个 - 表示一段不输出的代码,提供一个js语法执行环境,运算js后再将运算结果绑定到pug模板中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//- 时间格式化: 最长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.html




欢迎继续关注本系列博文的其他精彩文章
Node中间层实践(一)——基于NodeJS的全栈式开发
Node中间层实践(二)——搭建项目框架
Node中间层实践(三)——webpack配置
Node中间层实践(四)——模板引擎pug
Node中间层实践(五)——express-中间层的逻辑处理