Home » Node.js

Hello World in Node, Express and EJS (2) | Introduction to EJS

In this tutorial, we are going to learn about the EJS (Embedded JavaScript) with example of Hello world in Node, Express and EJS (part 2).
Submitted by Godwill Tetah, on June 27, 2019

Hi! Welcome to NODE AND EJS TEMPLATE ENGINE SERIES. Today, we will see another method how to write hello world using node, express and EJS?.

To install EJS and basic knowledge about it, please read this tutorial: Hello World in Node, Express and EJS (2) | Introduction to EJS

In our first method, we used res.render and then passed our EJS file.

Our ejs file contained html code.

EJS helps us embed JavaScript code, if statements and loops inside html.

Today, we'll use method where EJS uses JavaScript in html.

EJS uses the syntax <%= %> to represent JavaScript code in html.

For example:

<html>
	<h1>  <%= 5+5%>		<h1>
	<h2>    < 5+5> 		</h2>
</html>

Looking at the code above, the output for h1 will be 10 while that of h2 will be 5 + 5.

EJS renders (or treats) h2 as plain html and h1 as JavaScript which can also be used as a variable.

Open your text editor and type the following code, Save as app.js.

var express = require('express');
var ejs = require('ejs');
var app = express();
app.set('view engine', 'ejs');

app.get("/", function(req, res) {
    res.render("hello.ejs", {
        message: 'Hello wold! i am now using ejs '
    });

});
app.listen(3000, function() {
    console.log("server is listening!!!");
});

Now, let's create our EJS file.

Open a text editor and type the following code, Save as hello.ejs

<html>
<h1><%= message%><h1>
</html>
  • Create a folder in your app.js directory called views.
  • Cut and paste the EJS file in the views folder.
  • Take Note: The folder name views are not a random word I selected but it's the reserved folder name where express checks for template engine by default.
  • In our express server we used app.set() and passed in our template engine unlike our other examples.

Finally, initiate the app.js file and view the port in a browser. localhost:3000

EJS Image 2(1)

Or for those using nodemon, use

EJS Image 2(2)

EJS Image 2(3)

Thanks for coding with me! Feel free to drop a comment or question.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.