DEV Community

bellsofaba
bellsofaba

Posted on

Using Node.js to Dynamically add HTML Content

Introduction

Hi there, coder! Welcome to this tutorial. In it, you will follow an 8-step node.js lesson to learn how to create an application. This application responds to a collection each time a static html file is modified.

Information is sent from the server to the static html page with the aid of what is known as ejs. In this regard, ejs will serve as middleware. A Body Parser will also assist us in gathering data from a form and sending it to the collection for storage.

Let's get started!

Step 1: EJS Installation
First on the list is ejs installation. To achieve this, you will need to locate your root directory. This is done via the terminal by using:

cd <name of directory>
Enter fullscreen mode Exit fullscreen mode

After locating your root directory, enter the following command. Also to be executed in your terminal.

npm install ejs
Enter fullscreen mode Exit fullscreen mode

Step 2: Updating EJS as Your View Engine
When you are done with installing your ejs, you will need to set it as your view engine. The code that follows will help you achieve this part of the process.

app.set('view engine', 'ejs');
Enter fullscreen mode Exit fullscreen mode

Step 3: Directories Reorganization
You are doing great. Consider this is your tap on the back. Now that you have updated your view engine. It means there would likely be ejs file usage. But then, there isn't any ejs file just yet. Don't fret.

You will need to locate your files that have an extension of .html. When you do, rename them so that their new extension would go from .html to having extension names that end with .ejs.

When your new .ejs files are ready, you will need to move them to a location called views. Views is a folder that is likely in your root directory.

Step 4: Utilize EJS Variables
You deserve another tap on the back. You're are doing absolutely amazing. Let's move on to how we can use ejs variables. These would help in providing permission for you to get some data from your server file.

Here is an example code.

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>
<body>
    <%= variableName %>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 5: Sending Data to EJS File
Hopefully, you are getting the results you want. If not, please retrace these steps a notchback and pick up where you likely miss-stepped.

The next thing you will need to do is to use the render function.
An ejs file and data will be given to the render function.

Note: Keep in mind that this action should be done in your server file.

app.get("/", (req, res) => {
    res.render("home", { variableName: "Discover the secrets of ancient civilizations!" });
});
Enter fullscreen mode Exit fullscreen mode

Step 6: Getting Form Data with Body Parser
Now that you have sent data to the server file, you will need to capture form input values in your server file by installing a package known as Body Parser package. The following code is how you will achieve this.

Note: This would be in your terminal.

npm install body-parser
Enter fullscreen mode Exit fullscreen mode

Next, you want to add the following code in your server file. It helps you to use Body Parser:

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Enter fullscreen mode Exit fullscreen mode

Step 7: Handling Form Submission
This is the second to the last step in our process. Assuming you have a collection named data with items containing a title and content, you will want to update the route handlers in your server file as follows:

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

app.post("/", (req, res) => {
    const inputTitle = req.body.inputTitle;
    const inputContent = req.body.inputContent;
    data.push({
        title: inputTitle,
        content: inputContent
    });
    res.render("home", { data: data });
});
Enter fullscreen mode Exit fullscreen mode

Step 8: Create the Home Template
Now onto our last step. In your home.ejs file, display the title and content of each object in the data collection using a forEach loop. Include a form to submit new titles and content. Here's an example:

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>
<body>
    <% data.forEach(element => { %>
        <h2><%= element.title %></h2>
        <p><%= element.content %></p>
    <% }) %>
    <form action="/" method="post">
        <input type="text" placeholder="Title" name="inputTitle">
        <input type="text" placeholder="Content" name="inputContent">
        <button type="submit">Submit</button>
    </form>
</body>
</html
Enter fullscreen mode Exit fullscreen mode

Conclusion

You have made it to the end. Congrats. Hopefully, you have figured out how to build a node.js application that's responsive and does what you ask of it. Not the other way around.

You have just elevated your node.js development game and can continue to do so moving forward.

Go forth and prosper!

Top comments (0)