Using Template Engines in Express.js
Express.js·3 min read·Jan 1, 2025
In Express, a template engine is a module that facilitates the dynamic generation of HTML pages at runtime by combining static HTML markup with dynamic data.
In this lesson, we'll use the Mustache template engine available under the npm package name mustache-express:
$ npm i --save express mustache-expressSetting up the templates directory
In Express, template files are by convention placed in a directory with an explicit name, such as views or templates, located in the root directory of the project.
To tell Express where to find these templates, you can use the set() method of the application instance, which is used to modify the application settings:
app.set('views', path);Where:
-
'views'is the name of the application setting to modify. -
pathis the relative path to the directory containing the views.
Example
Unlock the Build RESTful APIs in Node.js module
Learn how to build real database-backed and framework-powered RESTful APIs with MySQL, Sequelize, and Express.
You get immediate access to:
- 37 focused lessons across MySQL, Sequelize, backend, and Express
- 4 real-world projects with commented solutions
- Ongoing updates to this bundle
- Lifetime access to this bundle