General Middleware

Render dynamic content in Nodejs with templates

Nodejs can render both static and dynamic content. To render static content, we just return the HTML file as response. Using express, it is possible with just few lines of code as shown below.

const express = require('express')
app = new express()
app.listen(3000, () => {
console.log('NodeJS started listening on port 3000')
})
const path = require('path')
app.get('/', (req, res) => {
res.sendFile( path.join(__dirname,'/index.html'))
})

However, to return dynamic content, we need to use templates. There are several templating engines available to use. Out of all, the Embedded JavaScript template or EJS is the most popular.

Using EJS, we can render a .ejs file to the client. The .ejs file is a simple HTML with some scriplets to represent dynamic values or content.

Follow step by step to implement the EJS.

Step 1. Install ejs and express

npm install ejs
npm install express

Step 2. Write the base code for the first .js file, usually named as index.js

const express = require("express");
const app = express();

app.listen(3000, () => {
  console.log("server started on port 3000");
});

Step 3. Specify the render engine by setting the “view engine” as “ejs”



const express = require("express");
const app = express();

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

app.listen(3000, () => {
  console.log("server started on port 3000");
});

Step 4. Render a .ejs file to the Client



const express = require("express");
const app = express();

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

app.post("/currentTemperature", (req, res) => {

res.render("showCurrentTemp", {
    celsiusValue: 30,
    fahrenheitValue: 86
})

})

app.listen(3000, () => {
  console.log("server started on port 3000");
});


In above code, upon request from client with URI /currentTemperature, we render a file called showCurrentTemp.ejs

Note that we don’t need to mention the file extension, as we already defined the “view engine” as “ejs”

In addition, we pass an object as a second argument to the render function. The keys of that object, can be used as dynamic values in the showCurrentTemp.ejs

Let’s look at the showCurrentTemp.ejs now.

Step 5. Write the showCurrentTemp.ejs and put it under “views” in the root directory. Nodejs will search for the file under “views” by default.

<!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>Document</title>
</head>
<body>
    <p style="font-size: 60px; color: blue;">Current Room Temperature in Celsius - <%=celsiusValue%></p>
    <p style="font-size: 60px; color: rgb(50, 50, 65);">Current Room Temperature in Fahrenheit - <%=fahrenheitValue%></p>
</body>
</html>

See how the .ejs file renders the dynamic values of celsiusValue and fahrenheitValue . Here is the output.

An important feature of the EJS

Instead of putting the complete HTML into one single .ejs file, best practice is to divide it into 3 parts.

  1. header.ejs
  2. footer.ejs
  3. showCurrentTemp.ejs [This includes the header.ejs and footer.ejs with include statements]

This is very convenient, especially to avoid repetitive code.

Here is how the above 3 files look like.

header.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>Document</title>
</head>
<body>

footer.ejs

</body>
</html>

showCurrentTemp.ejs

Look how the header.ejs and footer.ejs are included in this file.

<%- include('header.ejs') %>
<p style="font-size: 60px; color: blue;">Current Room Temperature in Celsius - <%=celsiusValue%></p>
<p style="font-size: 60px; color: rgb(50, 50, 65);">Current Room Temperature in Fahrenheit - <%=fahrenheitValue%></p>
<%- include('footer.ejs') %>

Dividing the templates into parts is completely optional, and it doesn’t change the way you render the final .ejs with all the includes in place.

Leave a Reply

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