Using EJS Template Engine With Node.js and ExpressJs

What is EJS?

EJS stands for Embedded JavaScript Templating is a templating language that lets you generate HTML markup and embed plain JavaScript into HTML files.

EJS enables us to have dynamic templates. We can use it both for server-side or client-side.

Basic Tags used in EJS:

Inside the tag, everything is treated as JavaScript Code.

  • <%   ‘Scriplet tag‘ for control-flow, no output.
  • <%=  Used to output the value into the template.
  • %>     Ending Tag.
  • <%-  Output the unescaped value into the template.

Now to start with EJS we need to install Ejs and Express:

npm install express --save
npm install ejs --save

The above command will install express and ejs.

Now with the dependencies installed. let’s set up our routes for the pages we need to render.

We need to create a views folder in our main project folder. The EJS will look into the views folder for the templates to render.

app.js

//require all the things we need.
var express=require("express");
var app=express();

//to serve the CSS file
app.use( express.static('public'));

//set EJS as templating engine
app.set("view engine","ejs");


//home page
app.get("/",(req,res)=>{
    res.render("home");
});

//posts page
app.get("/posts",(req,res)=>{
   
    var posts=[
        {title:"Post 1",author:"Suzy"},
        {title:"My adorable pet bunny",author:"Charlie"},
        {title:"Can you beileve this psomky",author:"Colt"}
    ];
    res.render("posts",{posts:posts});
})

//to start the server 
app.listen(8080,()=>{
    console.log('Server has Started')
});

Here, we set EJS as the view engine for our app using app.set(“view engine”,”ejs”); 

res.render() will look into the views folder for the view. So we write res.render(“home”)(this will render the HTML page). the home page should be in the views folder in the root directory

home.ejs (views/home)

<html>

<head>
    <title>homepage</title>
    <link rel="stylesheet" type="text/css" href="app.css">
   
</head>


<body>
    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRbCkSxeAzNOHVar8tgYDpe09guO-kY25CzsH02Q35s5-Qnyc6R">

<h1>This is the homepage</h1>
</body>
</html>

The home page will be rendered on request by the user.

Now if we visit http://localhost:8080 in our browser we can see the home page:

app.css (public/app)

body{
    background: yellow;
    color: purple;
}

app.css file is created in the public folder in the root directory.

Passing Data to Views:

Now to show dynamic content(javascript) in ejs we do the following :

Let’s define a list to pass to our posts page.

app.get("/posts",(req,res)=>{
   
    var posts=[
        {title:"Post 1",author:"Suzy"},
        {title:"My adorable pet bunny",author:"Charlie"},
        {title:"Can you beileve this psomky",author:"Colt"}
    ];
    res.render("posts",{posts:posts});
})

Here, we have created a list of ‘posts’.Now we will go into the posts page and use them to show the dynamic content.

posts.ejs(views/posts)

<html>

<head>
    <title>
        postspage
    </title>

    <link rel="stylesheet" type="text/css" href="app.css">
</head>

<body>
    <% for(var i=0; i<posts.length; i++) { %>
        <li>
            <%= posts[i].title %>-<strong>
                    <%=posts[i].author %>
                </strong>
        </li>

        <% } %>
</body>

</html>

On request by the user posts page will be rendered. To loop over our posts data we use ‘for‘ loop. for loop is inside <% Scriplet tag which will treat all the code inside this tag as normal javascript.

<%=posts[i].title %>  will output the title of the posts.

To Run the Program:

Type below command in your CLI:

node app.js

Now if we visit http://localhost:8080/posts in our browser we can see the posts page:

 

Leave a Reply

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