# 使用 Pug

URL: https://caijiao.org/express/chapter4/3-pug
Source: docs/express/chapter4/3-pug.md
Description: 本章节介绍如何在 Express 中使用 Pug 模板引擎，讲解 Pug 的基本语法、动态渲染方法，以及如何构建可维护的模板。

Pug（原名 Jade）是一个高效的模板引擎，使用缩进语法来生成 HTML。相比传统的 HTML，Pug 模板简洁且可读性高，广泛应用于 Express 应用中。

## 安装 Pug

首先，在项目中安装 Pug 模板引擎：

```bash
npm install pug
````

## 配置 Pug

在 Express 中设置 Pug 作为模板引擎，并配置视图文件夹：

```js
const express = require('express');
const path = require('path');
const app = express();

// 设置模板引擎为 Pug
app.set('view engine', 'pug');

// 设置视图文件夹路径
app.set('views', path.join(__dirname, 'views'));

app.listen(3000, () => {
  console.log('服务器启动在 http://localhost:3000');
});
```

## 渲染 Pug 模板

使用 `res.render()` 渲染 Pug 模板并传递数据：

```js
app.get('/', (req, res) => {
  res.render('index', { title: 'Express 和 Pug' });
});
```

### 创建 `views/index.pug` 模板

在 `views` 文件夹中创建一个名为 `index.pug` 的文件：

```pug
doctype html
html(lang="en")
  head
    meta(charset="UTF-8")
    title= title
  body
    h1 欢迎来到 #{title} 网站！
```

### 渲染结果

访问 `http://localhost:3000` 时，Express 会使用 `index.pug` 模板和传递的数据生成以下 HTML：

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Express 和 Pug</title>
  </head>
  <body>
    <h1>欢迎来到 Express 和 Pug 网站！</h1>
  </body>
</html>
```

## Pug 模板语法

Pug 语法与传统的 HTML 相比，简化了标记，并且不需要关闭标签。以下是一些常用的 Pug 语法：

### 1. HTML 元素

Pug 使用缩进语法代替标签，并且不需要闭合标签：

```pug
html
  head
    title Example Page
  body
    h1 Hello, World!
    p Welcome to Pug templates!
```

### 2. 变量插值

通过 `#{}` 插值语法插入变量：

```pug
h1 欢迎来到 #{title} 网站！
```

### 3. 条件判断

Pug 支持类似 [JavaScript](/javascript/) 的条件语句：

```pug
- if user.isLoggedIn
  p 欢迎回来，#{user.name}
- else
  p 请登录
```

### 4. 循环

使用 `each` 循环语法：

```pug
ul
  each item in items
    li= item
```

### 5. 注释

Pug 使用 `//` 来注释：

```pug
// 这是一个注释
```

### 6. 表单

Pug 支持简洁的表单语法：

```pug
form(action="/submit", method="POST")
  input(type="text", name="username")
  button(type="submit") 提交
```

## 渲染动态数据

在 Pug 模板中，动态数据通过 `locals` 对象传递。例如，在 `app.js` 中传递数据：

```js
app.get('/user/:name', (req, res) => {
  const name = req.params.name;
  res.render('user', { userName: name });
});
```

在 `views/user.pug` 模板中：

```pug
h1 用户名: #{userName}
```

## 总结

Pug 提供了简洁高效的模板语法，使得动态生成 HTML 页面变得更加直观和易于维护。通过结合 Pug 和 Express，你可以快速构建和渲染动态页面，提升开发效率和代码质量。
