Using EJS with Express – Installation, Boilerplate Code

EJS refers to Embedded Javascript. It is basically used for templating the javascript app. In this post, we gonna check out the basic express app using EJS for rendering data in the frontend.

Firstly we gonna install EJS and the setup the views folder for saving the template .ejs files.

Installing EJS

npm i ejs

Create folder named, views the .ejs files will be stored in this folder.

app.js

const express = require("express");
const bodyParser = require("body-parser");

const app = express();

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

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

    var today = new Date();
    var currrentDay = today.getDay();
    var day = "";

    if(currrentDay === 6 || currrentDay === 0 ){
        day = "Weekend";
    } else{
        day = "Weekday";
    }

    res.render("list", {kindOfDay: day});  //sending data

});


app.listen(3000, function(){
    console.log("Server started on port 3000");
})

views/list.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample EJS - Test App</title>
</head>
<body>

    <h1> It's a <%= kindOfDay %>!</h1>
    
</body>
</html>

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *