简介
Pug(之前称为 Jade)是一种高性能的模板引擎,它使用缩进 + 简洁语法来描述 HTML 结构。Pug 模板会被编译为 JavaScript 函数,可在 Node.js 环境中执行,也可以编译后在浏览器端使用。
适用场景:
- Node.js 服务端渲染(如 Express、Koa)
- 静态站点生成
- 前端模板快速开发
安装与使用
安装
命令行编译
1
| npx pug index.pug --pretty --out dist
|
在 Node.js 中使用(以 Express 为例)
1 2 3 4 5 6
| app.set('view engine', 'pug') app.set('views', './views')
app.get('/', (req, res) => { res.render('index', { title: '首页' }) })
|
基本语法
标签与文本
1 2
| <h1>Pug 入门</h1> <p>这是一个段落</p>
|
包含和模板继承
include(包含)
1 2
| include includes/head.pug include style.css
|
包含 Include | Pug 模板引擎中文文档 | Pug中文网
pugjs.cn
extends / block(模板继承)
1 2 3 4 5 6 7 8 9 10 11
| // layout.pug html head block head body block content // index.pug extends layout.pug
block content h1 首页内容
|
模板继承 Inheritance | Pug 模板引擎中文文档 | Pug中文网
pugjs.cn
注释
1 2
| // HTML 注释(会被渲染) //- Pug 注释(不会被渲染)
|
注释 Comment | Pug 模板引擎中文文档 | Pug中文网
pugjs.cn
属性(Attributes)
基本用法
1
| a(href='https://www.baidu.com') 百度
|
1
| <a href="https://www.baidu.com">百度</a>
|
多行属性
1 2 3 4 5
| input( type='checkbox' name='agreement' checked )
|
1
| <input type="checkbox" name="agreement" checked="checked" />s
|
特殊属性名(如前端框架)
1
| div(class='div-class' '(click)'='play()')
|
1
| <div class="div-class" (click)="play()"></div>
|
变量与插值
1 2 3
| - var title = 'Pug 示例' h1 #{title} p= title
|
条件渲染
1 2 3 4 5 6 7 8 9 10 11 12 13
| - var user = { description: 'foo bar baz' } - var authorised = false
#user if user.description h2.green 描述 p.description= user.description else if authorised h2.blue 描述 p.description 用户没有添加描述 else h2.red 描述 p.description 用户没有描述
|
1 2 3 4
| <div id="user"> <h2 class="green">描述</h2> <p class="description">foo bar baz</p> </div>
|
分支条件(case)
1 2 3 4 5 6 7 8
| - var friends = 7 case friends when 0 p 您没有朋友 when 1 p 您有一个朋友 default p 您有 #{friends} 个朋友
|
分支条件 Case | Pug 模板引擎中文文档 | Pug中文网
pugjs.cn
循环(Iteration)
1 2 3 4 5 6 7
| - var list = ['Vue', 'React', 'Svelte'] ul each item in list li= item ul for item in list li= item
|
Mixin(可复用组件)
1 2 3 4 5
| mixin button(text, type) button(class=type)= text
+button('确认', 'primary') +button('取消', 'default')
|
内联 HTML
1 2 3 4
| p. 这是一段 多行文本 <strong>支持 HTML</strong>
|
更多内容
Pug 模板引擎简介 | Pug 模板引擎中文文档 | Pug中文网
pugjs.cn