Template Engines in Express.js
⏱ Estimated reading time: 2 min
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
1. Setting Up a Template Engine
We’ll use EJS as an example.
-
Install EJS:
-
Set EJS as the view engine in
app.js:
2. Project Structure
views/index.ejs:
-
<%= %>– Output the value of a variable. -
<% %>– Execute JavaScript code without rendering output.
3. Passing Data to Templates
You can pass objects, arrays, and variables to your template:
views/users.ejs:
4. Using Partials
Partials are reusable pieces of templates, like headers or footers.
views/partials/header.ejs:
views/index.ejs:
-
<%- include('file') %>– Includes another template file.
5. Other Popular Template Engines
| 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 |
6. Key Points
-
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.
Register Now
Share this Post
← Back to Tutorials