<%= message %>
Welcome to our website. This content is dynamic and rendered with EJS.
Templating engines are an essential part of web development, enabling developers to generate dynamic HTML content on the server side. In this chapter, we will explore various templating engines in Express.js, starting from the basics and moving towards more advanced concepts. We will cover popular templating engines such as Pug, EJS, and Handlebars, providing detailed explanations, code examples, and output descriptions.
Bonus💡: Practical example at the end of article
Templating engines allow you to embed code within your HTML, making it possible to generate dynamic content. They are useful for:
Before using any templating engine, you need to set up an Express.js project.
1.Create a new project directory and initialize a Node.js project:
mkdir templating-example
cd templating-example
npm init -y
2. Install Express.js:
npm install express
3. Create an index.js
file and set up a basic Express server:
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
1. Install Pug:
npm install pug
2. Set Pug as the templating engine in your Express app:
app.set('view engine', 'pug');
app.set('views', './views');
Create a simple Pug template file in the views
directory named index.pug
:
doctype html
html
head
title= title
body
h1= message
Modify index.js
to render this template:
app.get('/', (req, res) => {
res.render('index', { title: 'Pug Example', message: 'Hello from Pug!' });
});
doctype html
: Defines the document type.html
, head
, title
, body
, h1
: HTML elements.title= title
, h1= message
: Injecting dynamic content using Pug syntax.Output: When you visit http://localhost:3000
, you will see:
Pug Example
Hello from Pug!
Conditionals and Loops:
doctype html
html
head
title= title
body
if user
h1 Welcome, #{user}!
else
h1 Welcome, Guest!
ul
each item in items
li= item
Modify index.js
:
app.get('/', (req, res) => {
res.render('index', {
title: 'Pug Example',
user: 'Alice',
items: ['Item 1', 'Item 2', 'Item 3']
});
});
Output :
Pug Example
Welcome, Alice!
- Item 1
- Item 2
- Item 3
1.Install EJS:
npm install ejs
2.Set EJS as the templating engine in your Express app:
app.set('view engine', 'ejs');
app.set('views', './views');
Create a simple EJS template file in the views
directory named index.ejs
:
<%= title %>
<%= message %>
Modify index.js
to render this template:
app.get('/', (req, res) => {
res.render('index', { title: 'EJS Example', message: 'Hello from EJS!' });
});
<%= title %>
and <%= message %>
: Injecting dynamic content using EJS syntax.Output: When you visit http://localhost:3000
, you will see:
EJS Example
Hello from EJS!
<%= title %>
<% if (user) { %>
Welcome, <%= user %>!
<% } else { %>
Welcome, Guest!
<% } %>
<% items.forEach(function(item) { %>
- <%= item %>
<% }); %>
Modify index.js
:
app.get('/', (req, res) => {
res.render('index', {
title: 'EJS Example',
user: 'Alice',
items: ['Item 1', 'Item 2', 'Item 3']
});
});
EJS Example
Welcome, Alice!
- Item 1
- Item 2
- Item 3
1.Install Handlebars and its Express integration:
npm install hbs
2.Set Handlebars as the templating engine in your Express app:
app.set('view engine', 'hbs');
app.set('views', './views');
Create a simple Handlebars template file in the views
directory named index.hbs
:
{{title}}
{{message}}
Modify index.js
to render this template:
app.get('/', (req, res) => {
res.render('index', { title: 'Handlebars Example', message: 'Hello from Handlebars!' });
});
{{title}}
and {{message}}
: Injecting dynamic content using Handlebars syntax.Output: When you visit http://localhost:3000
, you will see:
Handlebars Example
Hello from Handlebars!
{{title}}
{{#if user}}
Welcome, {{user}}!
{{else}}
Welcome, Guest!
{{/if}}
{{#each items}}
- {{this}}
{{/each}}
index.js
:
app.get('/', (req, res) => {
res.render('index', {
title: 'Handlebars Example',
user: 'Alice',
items: ['Item 1', 'Item 2', 'Item 3']
});
});
Handlebars Example
Welcome, Alice!
- Item 1
- Item 2
- Item 3
All three templating engines are performant, but there might be slight differences depending on the complexity of the templates and the nature of the application. Generally, the performance differences are negligible for most use cases.
Note : Same can be done in other templating engines as well.
Partials in EJS allow you to reuse pieces of your HTML code across different templates, which helps to keep your code DRY (Don’t Repeat Yourself). Common use cases for partials include headers, footers, and navigation bars.
First, let’s set up our project structure:
templating-example/
├── views/
│ ├── partials/
│ │ ├── header.ejs
│ │ ├── footer.ejs
│ ├── index.ejs
├── index.js
├── package.json
Ensure EJS is installed:
npm install ejs
Modify index.js
to configure EJS as the templating engine and set up routes to render the templates:
const express = require('express');
const app = express();
const port = 3000;
app.set('view engine', 'ejs');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('index', { title: 'EJS Partials Example', message: 'Hello from EJS with Partials!' });
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Create a file named header.ejs
in the views/partials
directory:
Create a file named footer.ejs
in the views/partials
directory:
Modify the main template index.ejs
to include the header and footer partials:
<%- include('partials/header') %>
<%= message %>
Welcome to our website. This content is dynamic and rendered with EJS.
<%- include('partials/footer') %>
<%- include('partials/header') %>
: Includes the header partial in the template. The <%-
syntax is used to include the raw output of the partial without escaping.<%- include('partials/footer') %>
: Includes the footer partial in the template.Start the server:
node index.js
Visit http://localhost:3000
in your browser. You should see a page with the header, main content, and footer.
index.js
const express = require('express');
const app = express();
const port = 3000;
app.set('view engine', 'pug');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('index', { title: 'Pug Example', message: 'Hello from Pug!' });
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
views/index.pug
doctype html
html
head
title= title
body
h1= message
index.js
const express = require('express');
const app = express();
const port = 3000;
app.set('view engine', 'ejs');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('index', { title: 'EJS Example', message: 'Hello from EJS!' });
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
views/index.ejs
<%= title %>
<%= message %>
index.js
const express = require('express');
const app = express();
const port = 3000;
app.set('view engine', 'hbs');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('index', { title: 'Handlebars Example', message: 'Hello from Handlebars!' });
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
views/index.hbs
{{title}}
{{message}}
In this chapter, we explored various templating engines used with Express.js, including Pug, EJS, and Handlebars. We started with the basics of setting up an Express.js project and then delved into the installation, setup, basic syntax, and advanced features of each templating engine. By comparing the different engines, we highlighted their unique features, strengths, and suitable use cases.Happy coding !❤️