NodeJS App with EJS Template

Our Goals –
• Create a Simple Webpage with the help of NodeJS and EJS Template

Assumption
We already have a NodeJs project “myschool” in our working directory. If you don’t have the project then please create it. We have discussed it on our previous tutorial.

To do so –
1. Open comand prompt at our working directory and install “ejs” by typing “npm install ejs –save”.
2. And the out put will be like –


3. The “package.json” file will looks like –

{
  "name": "myschool",
  "version": "1.0.0",
  "description": "My First Project in NodeJS",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Tanmay Sarkar",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.17.0",
    "ejs": "^2.5.6",
    "express": "^4.15.0"
  }
}

4. Create a folder “app_views” on root section of the project.
5. Now create 3 file on “app_views” folder and place the following ocde on each file.

6. For “header.ejs” file

<html>
 <head>
  <meta charset="UTF-8">
  <title>My EJS Template</title>
  <meta name="description" content="Sample Web tutorials for Node JS">
  <meta name="keywords" content="NodeJS,EJS">
  <meta name="author" content="Tanmay Sarkar">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

7. For “footer.ejs” file

</html>

8. For “home.ejs”

<% include header %>
<body>

<h1><%= topicHead %></h1>

</body>
<% include footer %>

9. For “app.js”

Note : In line 8 ‘home’ is the file name of “home.ejs”
10. Considering we have installed “nodemon” in our nodejs and run “nodemon”

11. Now browser will show our first EJS template based webpage @ http://localhost:5000/

12. And the console log is –

Source Code :

var express = require('express');
var parser = require('body-parser');
var path = require('path');
var app = express();
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'app_views'))
app.get('/',function(req,res){
	res.render('home',{
		topicHead : 'Hello From EJS Template'
	});
	console.log('user accessing Home page');
});
app.listen(5000,function(){
	console.log('server running on port 5000');
})

Thank you.

Related posts:

Leave a Reply

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