Skip to main content

Archive

Show more

Node.js Template Engines in Express.js

Node.js Template Engines in Express.js

Template engines are used in Express.js to generate HTML dynamically by merging data with HTML templates. Express.js supports various template engines, allowing you to choose the one that best fits your project's requirements and preferences.


1. Installing a Template Engine

To use a template engine in Express.js, you need to install the template engine module using npm:

npm install --save template-engine-name

Replace template-engine-name with the name of the template engine you want to use (e.g., EJS, Pug, Handlebars).


2. Configuring the Template Engine

Once installed, you need to configure Express.js to use the installed template engine:

const express = require('express');
const app = express();

// Set the template engine
app.set('view engine', 'template-engine-name');

Replace template-engine-name with the name of the installed template engine (e.g., 'ejs', 'pug', 'handlebars').


3. Rendering Templates

Once configured, you can render templates by passing data to the template engine's render function:

Example using EJS:

// Render the 'index.ejs' template with data
app.get('/', (req, res) => {
    res.render('index', { title: 'Express.js', message: 'Welcome to Express.js!' });
});

In this example, the 'index.ejs' template is rendered with the provided data (title and message).


4. Conclusion

Node.js template engines in Express.js provide a convenient way to generate dynamic HTML content by combining data with pre-defined templates. Whether you prefer EJS, Pug, Handlebars, or another template engine, Express.js offers flexibility and ease of integration to meet your project's needs.

Comments