A template engine allows you to generate dynamic HTML pages by embedding JavaScript logic into HTML.
Instead of sending static HTML files, you can render pages with data from your server, making your web applications interactive.
Express supports multiple template engines, such as:
EJS – Embedded JavaScript templates
Pug – Clean, indentation-based syntax
Handlebars – Logic-less templates
We’ll use EJS as an example.
Install EJS:
Set EJS as the view engine in app.js:
views/index.ejs:
<%= %> – Output the value of a variable.
<% %> – Execute JavaScript code without rendering output.
You can pass objects, arrays, and variables to your template:
views/users.ejs:
Partials are reusable pieces of templates, like headers or footers.
views/partials/header.ejs:
views/index.ejs:
<%- include('file') %> – Includes another template file.
| Engine | Features |
|---|---|
| EJS | Simple, syntax similar to HTML & JS |
| Pug | Indentation-based, clean and concise |
| Handlebars | Logic-less templates, reusable partials |
| Mustache | Minimalistic and easy to use |
Template engines help render dynamic content from the server.
Express makes it easy to switch between engines by setting app.set('view engine', 'engineName').
Using partials promotes reusable code.
Ideal for server-side rendered web applications.
Take quizzes related to this topic and see where you stand!
Start Quiz Now