![]() |
VOOZH | about |
EJS (Embedded JavaScript) is a popular templating engine for Node.js that allows you to generate HTML markup with plain JavaScript. It is particularly useful for creating dynamic web pages, as it enables you to embed JavaScript logic directly within your HTML.
EJS or Embedded Javascript Templating is a templating engine used by Node.js. Template engine helps to create an HTML template with minimal code. Also, it can inject data into an HTML template on the client side and produce the final HTML. EJS is a simple templating language that is used to generate HTML markup with plain JavaScript. It also helps to embed JavaScript into HTML pages.
To begin with, using EJS as templating engine we need to install EJS using the given command:
npm install express ejs --saveIt will install exxpress and ejs as dependency in the node.js project.
The default behavior of EJS is that it looks into the 'views' folder for the templates to render. So, let's make a 'views' folder in our main node project folder and make a file named "home.ejs" which is to be served on some desired requests in our node project. The content of this page is:
Now, we will render this page on a certain request by the user:
Now, the page home.ejs will be displayed on requesting localhost. To add dynamic content this render method takes a second parameter which is an object. This is done as:
Now, We will embed the name to the HTML page as:
It is used to embed dynamic content to the page and is used to embed normal JavaScript. Now embedding normal JavaScript:
The final HTML content:
Steps to run the program: After creating all the files go to the root directory of your project folder and run the below command
node index.js Type the node file_name.js command to run your program and see the output as displayed.
Output:
EJS is a powerful and flexible templating engine that enhances your Node.js applications by allowing you to generate dynamic HTML content with ease. Its simplicity and integration with Express make it an ideal choice for developers looking to build server-rendered web applications quickly. Whether you're developing a simple site or a complex web application, EJS provides the tools you need to create dynamic and interactive user interfaces.