How EJS works ?

In the previous article, we had gone through a brief introduction to Embedded JavaScript (EJS), and how it is a templating language. Now, in this article, we will have a glimpse of how EJS works and how you can use it.

How an EJS works

It's almost like having a little JavaScript module that can run JavaScript code inside an HTML file and have an extension of .ejs. So we get just HTML but with bits of JavaScript enclosed inside a special syntax. But what does this special syntax mean? Let's have a look.

Special Syntax

Special Syntax means that any code will get wrapped inside these EJS tags.

EJS tags

Some of the common EJS tags are listed below:-

  1. <%= %>

    Whatever goes in between the opening and closing parts of the tag will be interpreted as JavaScript. Also, there will be an output that's going to be put into that HTML or JS file. So it interprets JavaScript with an output.

    <%= variable %> => When this tag is rendered it will show the value of the variable.

    Eg:- name = "hashnode", then <%= name %>

    It show the value of the name that is hashnode on the website.

  2. <% %>

    Whatever goes in between the opening and closing parts of this tag, then it will execute as a JavaScript code. Inside the tag, we can write any JavaScript code and it will just treated like JavaScript code but it is interpreted as a JavaScript file. We can write JavaScript inside HTML.

    E.g.:- <% console.log("hello") %>

    It will not give output on the website when it is rendered. It will get evaluated but nothing will show up in the browser.

  3. <%- %>

    Whatever goes in between the opening and closing parts of this tag should be rendered and interpreted as HTML.

    Eg:- <%- <h1>Hello</h1> %>

    It will show a big hello of font size h1.

  4. <%% %%>

    It is an escape EJS tag. It will not interpreted as EJS text, just interpreted as plain text.

  5. <%# %>

    We can write EJS comments using this tag. It will stop the execution of what we have written inside this tag. Everything that goes inside this tag will be interpreted as a comment but not as a code.

  6. <%- include("<FILE NAME>") %>

    This allows us to insert another EJS file into this current JS file.

    Eg:- <%- include("header.ejs") %>

Let's use the EJS Tags:-

We will make a web application that will say whether it is a weekday or weekend and depending on it, it will give some advice

Prerequisite:-

Node.js must be installed on your local system.

Steps to make the web application:-

  1. Make a folder named days-prediction on your system, open it in any code editor and open the terminal in it. Install the following dependencies:-

    1. nodemon:- used to automatically reload the page

    2. express

    3. ejs

    by using npm as shown below

     npm i nodemon
     npm i express
     npm i ejs
    
  2. Now make a file name server.js and make a new folder name views, inside views make a file named index.ejs

File Structure:-

  1. Now inside server.js

     //server.js
    
     const express = require("express")
    
     const app = express();
     const port = 3000;
    
     app.get("/", function(req, res){
    
         //the below lines will get the current date
         const today = new Date();
                     // OR
         // const today = new Date("July 16, 2023");
         const day = today.getDay();
    
         let type = "a weekday";
         let advice = "time to do some hard work";
    
         if(day === 0 || day === 6){
             type = "the weekend";
             advice = "time to take some rest";
         }
    
         //console.log(day);
         res.render("index.ejs", {
    
             // object 1
             dayType: type,
             advice: advice,
         });
     });
    
     app.listen(port,function() {
         console.log(`Server is running on port ${port}.`);
     });
    

    We have import the express module and start the server on port number 3000 (Type nodemon server.js in terminal and it will start the server and write localhost:3000 in your browser)

    Here we have used res.render instead of res.sendFile as res.sendFile will only send static response but res.render can also send dynamic response too.

    res.render will take two things, one is the file name which has to be render and second will be the object which has to be passed in the file.

  2. Now in index.ejs

     <!--index.ejs-->
    
     <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>Week Day</title>
     </head>
     <body>
         <!-- <%=  %>:- output a value in between opening and closing ejs bracklets -->
         <h1>Hey, its <%= dayType %>, <%= advice %>!</h1>
     </body>
     </html>
    

    In h1 tag the value of variable dayType and advice will get retrieve from server.js

  3. In browser we will get the below response

Since it is the weekend I am getting the dayType and advice according to that. If you are running it on a weekday you will receive a response according to that.

Conclusion

In this blog post, we have learned about EJS, a templating language that is often used with Node.js. We saw an example of how to use EJS to create a simple HTML page. We also learned about some of the benefits of using EJS, such as its simplicity and flexibility.

If you are interested in learning more about EJS, there are many resources available online. You can also find many examples of EJS templates that you can use as a starting point. Please comment below if you have any queries or facing problems in implementing the Project.

Pic Reference: https://medium.com/swlh/basic-routing-in-javascript-fb3e51a3a57b

17
Subscribe to my newsletter

Read articles from Kansariwala Hetashri Dhavalkumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Kansariwala Hetashri Dhavalkumar
Kansariwala Hetashri Dhavalkumar

I am a Front-End Developer, Open Source Contribution.