在 Express 中使用模板引擎
模板引擎能够让你在应用中使用静态模板文件。运行时,模板引擎会将模板文件中的变量替换为实际值,并把模板转换成HTML文件发送至客户端。这种方式能够简化HTML页面的开发。
The Express application generator uses Pug as its default, but it can generate apps configured for Handlebars-compatible engines such as hbs, EJS, among others.
For apps created by the generator, these settings are added to the generated app.js. For apps you create without the generator, set the following application setting properties yourself:
views,模板文件所在的目录。例如:app.set('views', './views')。该配置默认为应用根目录下的views目录。view engine,要使用的模板引擎。例如,要使用 Pug 模板引擎:app.set('view engine', 'pug')。
Then install the corresponding Express-compatible template engine npm package; for example to install Pug:
npm install pug --saveyarn add pugpnpm add pugbun add pugCaution
符合 Express 规范的模板引擎如 Pug会导出一个名为__express(filePath, options, callback)的函数,res.render()会调用该函数来渲染模板代码。
有些模板引擎并不遵循此规范。 @ladjs/consolidate库遵循此规范,对所有主流Node.js模板引擎进行了统一封装,因此可在Express中无缝使用。
For example, install hbs or any other Express-compatible Handlebars view engine instead of the raw handlebars package by itself.
设置视图引擎后,你无需在应用中指定引擎或加载模板引擎模块; Express 会在内部自动加载该模块,例如:
app.set('view engine', 'pug');然后,在views目录中创建一个名为index.pug的Pug模板文件,内容如下:
html head title= title body h1= message创建一条路由来渲染index.pug文件。如果未配置view engine属性,则必须指明视图文件的后缀名。否则可以省略文件后缀。
app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' });});import { type Request, type Response } from 'express';
app.get('/', (req: Request, res: Response) => { res.render('index', { title: 'Hey', message: 'Hello there!' });});当访问首页时,index.pug 文件会被渲染成 HTML。
视图引擎缓存不会缓存模板渲染后的输出内容,仅缓存原始模板文件本身。即便开启缓存,每次请求视图仍会重新渲染。