Use EJS as Template Engine in Node.js
npm install ejs --save
Note: npm in the above commands stands for the node package manager, a place where install all the dependencies. –save flag is no longer needed after Node 5.0.0 version, as all the modules that we now install will be added to dependencies.
Now, the first thing we need to do is to set EJS as our templating engine with Express which is a Node.js web application server framework, which is specifically designed for building single-page, multi-page, and hybrid web applications. It has become the standard server framework for node.js.
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 request in our node project. The content of this page is:
Now, we will render this page on a certain request by the user as:
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 name to HTML page as:
The final HTML content:
Steps to run the program:
- After creating all the files go to the root directory of your project folder.
- Run command prompt in this directory.
- Type node file_name.js command to run your program and see the output as displayed.