,

Creating Dynamic Pages with EJS Templating Engine in Node.js and Express.js: Chapter 3

Posted by

Node.js & Express.js Series | Chapter 3 | Dynamic Pages With Templating Engine EJS

Node.js & Express.js Series

Chapter 3: Dynamic Pages With Templating Engine EJS

Welcome to Chapter 3 of our Node.js & Express.js Series! In this chapter, we will learn about creating dynamic web pages using the EJS templating engine.

What is EJS?

EJS, or Embedded JavaScript, is a simple templating language that lets you generate HTML markup with plain JavaScript. It allows you to embed JavaScript code within your HTML templates, making it easy to create dynamic content based on data from your server.

Using EJS with Express.js

To use EJS with Express.js, you need to install the EJS package using npm:

    npm install ejs
  

Once installed, you can set the view engine for your Express.js application to EJS in your server file:

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

Creating Dynamic Pages

With EJS, you can create dynamic web pages by embedding JavaScript code within your HTML templates. For example, you can use EJS to loop through an array of data and display it in a list:

    <ul>
  <% data.forEach(function(item) { %>
    <li><%= item %></li>
  <% }); %>
</ul>
  

Passing Data to EJS Templates

You can pass data from your server to your EJS templates using the res.render method in Express.js:

    app.get('/', function(req, res) {
  res.render('index', { data: ['apple', 'banana', 'cherry'] });
});
  

In this example, we are passing an array of fruits to the index template, which can then be used to dynamically generate the HTML content.

Conclusion

EJS is a powerful templating engine that makes it easy to create dynamic web pages with Node.js and Express.js. In this chapter, we have learned how to use EJS to create dynamic content and pass data from the server to the client. In the next chapter, we will explore more advanced features of EJS and how to use it to build more complex web applications.

Stay tuned for the next chapter in our Node.js & Express.js Series!

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@muhammadmohsinhussain5428
6 months ago

Great work dear. Thanks for making this useful video.

@thezuraiz
6 months ago

Future GFX Mentor of Node Express..👍