Pug.js 教程
最后修改于 2023 年 10 月 18 日
Pug.js 教程介绍了 Pug 模板引擎。
Pug
Pug 是一个 JavaScript 模板引擎。它是一个高性能模板引擎,深受 Haml 影响,并使用 JavaScript 实现,适用于 Node.js 和浏览器。Pug 以前称为 Jade。
模板引擎
模板引擎或模板处理器是一种旨在将模板与数据模型相结合以生成文档的库。模板引擎通常用于生成大量电子邮件、在源代码预处理中,或生成动态 HTML 页面。
我们创建一个模板引擎,在其中定义静态部分和动态部分。动态部分稍后将被数据替换。渲染函数随后会将模板与数据结合起来。
设置 Pug.js
首先,我们安装 Pug.js。
$ npm init -y
我们启动一个新的 Node 应用程序。
$ npm i pug
我们使用 nmp i pug 命令安装 pug 模块。
Pug.js 从字符串渲染
我们从一个非常简单的例子开始,它从一个字符串进行渲染。
import { render } from 'pug';
const template = 'p #{name} is a #{occupation}';
const data = { 'name': 'John Doe', 'occupation': 'gardener' };
const output = render(template, data);
console.log(output);
该示例显示了来自字符串模板的输出。
import { render } from 'pug';
我们从 pug 模块加载 render 函数。
const template = 'p #{name} is a #{occupation}';
这是我们简单的字符串模板。第一个值是要渲染的标签。此外,我们添加了两个变量:name 和 occupation。为了输出这些变量,我们使用 #{} 语法。
const data = { 'name': 'John doe', 'occupation': 'gardener' };
这是我们传递给模板引擎的数据。
const output = render(template, data);
render 函数接受一个模板字符串和上下文数据。它将两者编译成最终的字符串输出。
$ node app.js <p>John Doe is a gardener</p>
Pug.js compileFile
compileFile 函数将 Pug 模板从文件编译成一个函数,该函数可以使用不同的局部变量多次渲染。
p Hello #{name}!
这是模板文件;它具有 .pug 扩展名。
import { compileFile } from 'pug';
const cfn = compileFile('template.pug');
const res = cfn({'name': 'John Doe'});
console.log(res);
const res2 = cfn({'name': 'Roger Roe'});
console.log(res2);
我们将模板编译成一个函数,并使用两个不同的局部数据调用该函数。
$ node app.js <p>Hello John Doe!</p> <p>Hello Roger Roe!</p>
Pug.js renderFile
renderFile 函数从文件编译 Pug 模板,并使用局部变量将其渲染为 HTML 字符串。
doctype html
html
body
ul
li Name: #{name}
li Occupation: #{occupation}
在模板中,我们有一个带有无序列表的小 HTML 文档。我们有两个变量。
import { renderFile } from 'pug';
const options = { 'pretty': true }
const locals = { 'name': 'John doe', 'occupation': 'gardener', };
const res = renderFile('template.pug', Object.assign(locals, options));
console.log(res);
我们使用 Object.assign 合并局部变量和选项;
const options = { 'pretty': true }
在选项映射中,我们设置了美化打印。(请注意,此选项已弃用。)
$ node app.js
<!DOCTYPE html>
<html>
<body>
<ul>
<li>Name: John doe</li>
<li>Occupation: gardener</li>
</ul>
</body>
</html>
Pug.js 传递数据列表
在下面的示例中,我们将一个数据列表传递给模板引擎并进行处理。
doctype html
html
body
ul
each e in names
li= e
在模板中,我们使用 each 形式来遍历传递给模板的数据列表。
import { renderFile } from 'pug';
const names = ['John Doe', 'Roger Roe', 'Paul Smith', 'Rebecca Jordan'];
const res = renderFile('template.pug', { 'names': names });
console.log(res);
我们定义了一个名称列表。该列表使用 names 选项在选项中传递给模板引擎。
Pug.js 条件语句
条件语句使用 if/else 关键字创建。
doctype html
html
head
style.
.emp { background: lightGreen }
body
if emp
p.emp Today is #{today}
else
p Today is #{today}
在模板中,我们根据 emp 选项显示一个强调段落。
style.
使用点语法,我们可以将文本块传递给标签。
import { renderFile } from 'pug';
import { writeFileSync } from 'fs';
const today = new Date().toLocaleDateString()
const emp = false;
const output = renderFile('template.pug', {'today': today, 'emp': emp});
writeFileSync('index.html', output);
我们获取当前数据,并通过 emp 变量将其传递给模板引擎。emp 确定输出是否被强调。生成的输出使用 writeFileSync 写入文件。
Pug.js 表格
在下面的示例中,我们从 CSV 文件读取数据,并在 HTML 表格中渲染它。
$ npm i csv
我们使用 csv 模块来处理 CSV 数据。
id,name,price 1,Audi,52642 2,Mercedes,57127 3,Skoda,9000 4,Volvo,29000 5,Bentley,350000 6,Citroen,21000 7,Hummer,41400 8,Volkswagen,21600 9,Toyota,26700
此 CSV 数据在 HTML 表格中呈现。
doctype html
html
body
table
thead
tr
each header in headers
th= header
tbody
each field in fields
tr
td= field.id
td= field.name
td= field.price
数据显示在 HTML 表格中。
td= field.id
td= 语法插值字段。
import { renderFile } from 'pug';
import { readFileSync, writeFileSync } from 'fs';
import pkg from 'csv';
const { parse } = pkg;
const csvData = readFileSync('cars.csv').toString();
parse(csvData, { columns: true }, (e, records) => {
const headers = Object.keys(records[0]);
const template = 'template.pug';
const options = { 'fields': records, 'headers': headers };
const res = renderFile(template, options);
writeFileSync('index.html', res);
});
我们读取并解析 CSV 数据。我们将 CSV 数据分成标头和记录。
Pug.js 与 Express.js
在下一个示例中,我们将 Pug.js 与 Express.js Web 框架集成。
html
body
p Today is #{today}
该模板放置在 views 目录中。
import express from "express";
const app = express();
app.set('view engine', 'pug');
app.get("/today", (req, res) => {
let today = new Date();
res.render("index", {today: today});
});
app.use((req, res) => {
res.statusCode = 404;
res.end("404 - page not found");
});
app.listen(3000, () => {
console.log("Application started on port 3000");
});
该示例是一个小型 Web 应用程序,它显示当前日期。
app.set('view engine', 'pug');
我们告诉 Express 使用 Pug。
app.get("/today", (req, res) => {
let today = new Date();
res.render("index", {today: today});
});
我们为 /today 路由渲染 index 模板。
来源
在本文中,我们使用 Pug.js 从 Pug 模板和数据生成 HTML 文档。