Use Template Engines in Express

Express·2 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-express

Set 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.
  • path is the relative path to the directory containing the views.

Example

Let's consider this project's directory structure:

project├── app.js└── templates

Unlock the program 🚀

Pay once, own it forever.

€79

30-day money-back guarantee

  • 13 modules
  • 113 lessons with full-code examples
  • 29 projects with commented solutions
  • All future lesson and project updates
  • Lifetime access

By submitting this form, you agree to the Terms & Conditions and Privacy Policy.