Using template engines with Express在Express中使用模板引擎

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.模板引擎使您能够在应用程序中使用静态模板文件。在运行时,模板引擎将模板文件中的变量替换为实际值,并将模板转换为发送给客户端的HTML文件。 This approach makes it easier to design an HTML page.这种方法使设计HTML页面变得更加容易。

The Express application generator uses Pug as its default, but it also supports Handlebars, and EJS, among others.Express应用程序生成器默认使用Pug,但它也支持HandlebarsEJS等。

To render template files, set the following application setting properties, in the default app.js created by the generator:要渲染模板文件,请在生成器创建的默认app.js中设置以下应用程序设置属性

Then install the corresponding template engine npm package; for example to install Pug:然后安装相应的模板引擎npm包;例如安装Pug:

$ npm install pug --save

Express-compliant template engines such as Pug export a function named __express(filePath, options, callback), which res.render() calls to render the template code.Pug等Express兼容的模板引擎导出一个名为__express(filePath, options, callback)的函数,该函数调用res.render()来渲染模板代码。

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.一些模板引擎不遵循此约定。@ladjs/consolidate库遵循这一约定,映射了所有流行的Node.js模板引擎,因此在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:设置视图引擎后,您不必在应用程序中指定引擎或加载模板引擎模块;Express在内部加载模块,例如:

app.set('view engine', 'pug')

Then, create a Pug template file named index.pug in the views directory, with the following content:然后,在views目录中创建一个名为index.pug的Pug模板文件,内容如下:

html
  head
    title= title
  body
    h1= message

Create a route to render the index.pug file. 创建一个路由来渲染index.pug文件。If the view engine property is not set, you must specify the extension of the view file. Otherwise, you can omit it.如果未设置view engine属性,则必须指定view文件的扩展名。否则,您可以省略它。

app.get('/', (req, res) => {
  res.render('index', { title: 'Hey', message: 'Hello there!' })
})

When you make a request to the home page, the index.pug file will be rendered as HTML.当您向主页发出请求时,index.pug文件将呈现为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.视图引擎缓存不缓存模板输出的内容,只缓存底层模板本身。即使缓存打开,每次请求都会重新呈现视图。