In Express.js, templates are typically used to render dynamic content and generate HTML pages dynamically.
There are several template engines available for Express.js, such as Pug (formerly Jade), EJS (Embedded JavaScript), Handlebars, and more.
Here's an example using the EJS template engine:
Template Syntax: Each template engine has its syntax for embedding dynamic content, including variables, conditionals, loops, and partials.
Layouts and Partials: Template engines support layouts and partials, allowing us to define reusable layouts of markup and apply them across multiple templates.
Helpers: Template engines provide helper functions to perform common tasks like manipulating strings, formatting dates, and more.
Dynamic Content: Templates enable us to embed dynamic data into HTML templates, allowing us to generate personalized content for each request.
Code Reusability: Templates allow us to reuse HTML structures across multiple templates, prevent from code duplication and improving maintainability.
Consistency: Templates help maintain consistency in design and layout across different pages of your application.
npm install ejs
const express = require('express'); const app = express(); const PORT = 3000; // Set the view engine to EJS app.set('view engine', 'ejs'); // Set the views directory app.set('views', __dirname + '/views'); // Example route that renders an EJS template app.get('/', (req, res) => { res.render('index', { message: 'Hello, Express.js with EJS!' }); }); app.listen(PORT, () => { console.log(`Server is running on port ${port}`); });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Express.js with EJS</title> </head> <body> <h1><%= message %></h1> </body> </html>
node your-app-file.js
Visit http://localhost:3000 in your browser, and see a page with the message "Hello, Express.js with EJS!".
npm install pug
const express = require('express'); const app = express(); app.set('view engine', 'pug');
doctype html html head title First Express App body h1 Welcome to First Express App Project Setup Dashboard p Hello, #{fullname}!
render the Pug template and pass dynamic data.
app.get('/', (req, res) => { res.render('index', { fullname: 'Alice Collin' }); });
We set Pug as the view engine using app.set('view engine', 'pug').
We create a simple Pug template (index.pug) that displays a welcome message with a dynamic `fullname`.
In the route handler for the root path (/), we render the index.pug template and pass a `fullname` variable with the value 'Alice Collin' to populate the dynamic content.