Open In App

Importance of View Engines in server-side rendering(SSR)

A view engine is a tool used in web development to create dynamic HTML content based on data from the server. It acts as a template processor that allows you to integrate data with predefined HTML templates easily.

In this article, we will learn about the Importance of view engines on server side rendering with example.

Importance of view engines in Server-Side Rendering

View engines are important for server-side rendering (SSR) because they allow you to create dynamic web pages by putting variables, loops, and other logic into HTML templates. It makes easier to keep your code organized and readable.

It is a combination of HTML tags, server controls and a programming language. It works inside the application to render views to the browser or to the user. The main job of the view engine is to compile components and templates into a set of instructions that can be understood and rendered by the browser.

Features of View Engine

Steps to Implement View Engine(EJS) in Express.js

Step 1: Create a NodeJS application using the following command:

npm init -y

Step 2: Install required Dependencies:

 npm i ejs express

The updated dependencies in package.json file will look like:

"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.2"
}

Folder Structure:

wer

Folder Structure

Example: The below example is demonstrating the EJS View Engine for Express.

<!-- views/index.ejs -->

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>EJS Example</title>
    <style>
        h1 {
            color: green;
        }
    </style>
</head>

<body>
    <h1>GeeksForGeeks | EJS View Engine</h1>
    <h2>Welcome, <%= name %>
            </h1>
            <p>Your email is: <%= email%>
            </p>
</body>

</html>
// index.js 

const express = require('express');
const path = require('path');
const app = express();
const port = 3000;

app.set('view engine', 'ejs');

app.set('views', path.join(__dirname, 'views'));

app.get('/', (req, res) => {

    const data = {
        name: "jaimin",
        email: "jaimin@gmail.com"
    };

    res.render('index', data);
});

app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`);
});

Step 4: To run the application use the following command

node index.js 

Output: Now go to http://localhost:3000 in your browser:

ejs-viewengine

Article Tags :