在 Express 中使用模板引擎
一个_模板引擎_使你能够在应用中使用静态模板文件。在运行时,模板引擎会将模板文件中的变量替换为实际的值,并将模板转换为发送给客户端的HTML文件。这种方法使设计HTML页面更容易。
🌐 A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.
Express 应用生成器 使用 Pug 作为默认模板,但它也支持 Handlebars 和 EJS 等其他模板。
🌐 The Express application generator uses Pug as its default, but it also supports Handlebars, and EJS, among others.
要渲染模板文件,请在生成器创建的默认 app.js 中设置以下应用设置属性:
🌐 To render template files, set the following application setting properties, in the default app.js created by the generator:
views,模板文件所在的目录。例如:app.set('views', './views')。默认情况下,该目录位于应用根目录下的views目录。view engine,要使用的模板引擎。例如,要使用 Pug 模板引擎:app.set('view engine', 'pug')。
然后安装相应的模板引擎 npm 包;例如,要安装 Pug:
🌐 Then install the corresponding 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() 会调用它来渲染模板代码。
🌐 Express-compliant template engines such as Pug export a function named __express(filePath, options, callback),
which res.render() calls to render the template code.
一些模板引擎不遵循此约定。[@ladjs/consolidate] 库通过映射所有流行的 Node.js 模板引擎来遵循此约定,因此可以在 Express 中无缝工作。
🌐 Some template engines do not follow this convention. The @ladjs/consolidate library follows this convention by mapping all of the popular Node.js template engines, and therefore works seamlessly within Express.
设置视图引擎后,你无需在应用中指定引擎或加载模板引擎模块;Express 会在内部加载该模块,例如:
🌐 After the view engine is set, you don’t have to specify the engine or load the template engine module in your app; Express loads the module internally, for example:
app.set('view engine', 'pug');然后,在 views 目录中创建一个名为 index.pug 的 Pug 模板文件,内容如下:
🌐 Then, create a Pug template file named index.pug in the views directory, with the following content:
html head title= title body h1= message创建一个路由来渲染 index.pug 文件。如果未设置 view engine 属性,则必须指定 view 文件的扩展名。否则,可以省略它。
🌐 Create a route to render the index.pug file. If the view engine property is not set,
you must specify the extension of the view file. Otherwise, you can omit it.
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。
🌐 When you make a request to the home page, the index.pug file will be rendered as HTML.
视图引擎缓存不会缓存模板输出的内容,只会缓存模板本身。即使缓存开启,每次请求时视图仍会重新渲染。
🌐 The view engine cache does not cache the contents of the template’s output, only the underlying template itself. The view is still re-rendered with every request even when the cache is on.