Home »
Node.js
Node and EJS project (1)
Here, we are implementing a small project based on Node.js and EJS (Embedded JavaScript).
Submitted by Godwill Tetah, on July 12, 2019
Hello! In the last articles, we spoke much about EJS template engine. Let's take some time and see how it can be applicable in a small project?
Take Note! You should have Node.js installed in your before you can start using EJS in this article.
To download Node JS, visit nodejs.org, then install.
* BASIC NODE.JS/EXPRESS KNOWLEDGE REQUIRED
To begin, ensure you have EJS and express installed via npm.
To install EJS, simply open a terminal/command prompt and type the following command:
npm install ejs
or
npm install ejs –save
Let's begin by creating our server.js file.
Open your text editor and type the following code, save as server.js.
// load the things we need
var express = require('express');
var app = express();
// set the view engine to ejs
app.set('view engine', 'ejs');
// use res.render to load up an ejs view file
// index page
app.get('/', function(req, res) {
res.render('pages/index');
});
// about page
app.get('/about', function(req, res) {
res.render('pages/about');
});
app.listen(8080);
console.log('8080 is the magic port');
Now let's create our ejs files.
Open a text editor and type the following code, save as home.ejs
- Next, Create a folder called Views.
- In the views folder, create 2 new folders: the pages and partials folder.
- In the pages folder, create 2 new ejs files.
Open your text editor and type the following code, save as about.js.
<!DOCTYPE html>
<html lang="en">
<head>
<% include ../partials/head %>
</head>
<header>
<% include ../partials/header %>
</header>
About Me!!!
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
Open a text editor and type the following code again, save as index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<% include ../partials/head %>
</head>
<header>
<% include ../partials/header %>
</header>
About Me!!!
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
In the partials folder create the following ejs files, Footer.ejs
<div style="background-color:black; color:white; padding:8px;">
<center><pre>Copyright 2019! Godwill Tetah || Tutor @ Includehelp.com
</div>
Head.ejs
<html>
<head>
<title> EJS</title>
</head>
<body>
<div style="background-color:yellow; padding:50;">
<h2> <center> EJS IS COOL!!</h2>
</div>
</body>
</html>
Header.ejs
<center>
<pre>
<a href="/about">About</a>
<a href="/">Home</a>
</pre>
</center>
Finally, initiate the app.js file with node app.js in a terminal and view the port in a browser.
Output
Thanks for coding with me! Feel free to drop a comment or question.