模式切换
Web 模板引擎
Web 模板引擎(Template Engine)用于动态生成 HTML 页面,它能够将服务器端的数据动态地嵌入到模板中,并返回最终的 HTML 给客户端。常见的模板引擎有 EJS 和 Pug,它们为 Web 开发提供了灵活和高效的模板渲染解决方案。
EJS 模块
ejs 模块的渲染方法
EJS(Embedded JavaScript)是一种基于 JavaScript 的模板引擎,它允许在 HTML 文件中嵌入 JavaScript 代码,动态生成 HTML 页面。在 Node.js 中,使用 ejs
模块来处理模板渲染。
安装 EJS:
bash
npm install ejs
基本渲染方法:
javascript
const ejs = require('ejs');
const path = require('path');
// 渲染模板
ejs.renderFile(path.join(__dirname, 'views', 'template.ejs'), { name: 'John Doe' }, (err, str) => {
if (err) {
console.error(err);
} else {
console.log(str); // 返回渲染后的 HTML 字符串
}
});
在这个例子中,renderFile
方法渲染一个 EJS 模板,并将数据传递给模板,生成最终的 HTML 字符串。
ejs 模块的数据传递
EJS 模板引擎支持通过传递一个 JavaScript 对象来将数据传递给模板:
模板文件(template.ejs):
html
<h1>Hello, <%= name %>!</h1>
Node.js 渲染代码:
javascript
ejs.renderFile(path.join(__dirname, 'views', 'template.ejs'), { name: 'John Doe' }, (err, str) => {
if (err) {
console.error(err);
} else {
console.log(str); // 输出:<h1>Hello, John Doe!</h1>
}
});
在上面的例子中,<%= name %>
是 EJS 的语法,用于插入 JavaScript 变量 name
的值。
Pug 模块
Pug(原名 Jade)是另一个流行的模板引擎,它采用简洁的缩进语法来代替传统的 HTML 标签语法。Pug 非常适合快速开发和减少代码冗余。
pug 模块的渲染方法
Pug 模板可以通过 pug
模块在 Node.js 中进行渲染。
安装 Pug:
bash
npm install pug
基本渲染方法:
javascript
const pug = require('pug');
// 编译模板
const compiledFunction = pug.compileFile('views/template.pug');
// 渲染模板并传递数据
const html = compiledFunction({ name: 'John Doe' });
console.log(html);
在这个例子中,compileFile
方法编译 Pug 模板文件,返回一个渲染函数,调用该函数并传递数据后生成 HTML 字符串。
pug 模块的数据传递
Pug 模板引擎允许通过对象的形式传递数据:
模板文件(template.pug):
pug
h1 Hello, #{name}!
Node.js 渲染代码:
javascript
const html = compiledFunction({ name: 'John Doe' });
console.log(html); // 输出:<h1>Hello, John Doe!</h1>
在 Pug 模板中,#{name}
用于插入数据对象中 name
的值。Pug 提供了更加简洁的语法,相比传统的 HTML,它省略了很多不必要的符号,如闭合标签等。