How to Setup View Engine in Node.js ? – GeeksforGeeks

View engines are useful for rendering web pages. There are many view engines available in the market like Mustache, Handlebars, EJS, etc but the most popular among them is EJS which simply stands for Embedded JavaScript. It is a simple templating language/engine that lets its user generate HTML with plain javascript.

Installation of ejs module:

  1. You can visit the link Install ejs module. You can install this package by using the following command.
    npm install ejs
  2. After installing multer you can check your ejs version in command prompt using the command.
    npm version ejs
  3. After that, you can just create a folder and add a file for example app.js, To run this file you need to run the following command.
    node app.js
  4. To setup view engine, you need the write this middleware in your index.js as follow:
    app.set('views', path.join(__dirname, 'views'))
    app.set('view engine', 'ejs')

    where path is the global object and __dirname holds current directory address. Views is the folder where our all web pages will be kept.

  5. Now create a EJS file like Demo.ejs and put this file in views folder.

Filename: Demo.ejs




<!DOCTYPE html>

<html>

<head>

    <title>View Engine Demo</title>

</head>

<body>

  

  <!- For printing variable these

      tags are used: <%= %>  -->

  <h1> <%= title %> </h1>

     

  <!- For business logic these

      tags are used: <% %> -->

  <% if(true){ %>

      <h4>Greetings from geeksforgeeks</h4

  <% } %>

</body>

</html>



Filename: app.js




const express = require('express')

const path = require('path')

const app = express()

  

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

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

  

app.get('/', function(req, res){

  

    

    

    res.render('Demo', {

        title: 'View Engine Demo'

    })

})

  

app.listen(8080, function(error){

    if(error) throw error

    console.log("Server created Successfully")

})



Steps to run the program:

  1. The project structure will look like this:
    project structure
  2. Make sure you have ‘view engine’ like I have used “ejs” and also install express using the following commands:
    npm install ejs
    npm install express
  3. Run app.js file using below command:
    node app.js

    Output of above command

  4. Open browser and type this URL:
    http://localhost:8080/
  5. Then you will see the Demo.ejs page as shown below:
    Ejs Demo Page

So this is how you can setup a view engine in node js. There are many other engines exist like Handlebars, Mustache, etc.

My Personal Notes

arrow_drop_up