Home » Node.js

EJS for loops

for loops in EJS: In this tutorial, we are going to learn about the for loops with examples in EJS.
Submitted by Godwill Tetah, on July 12, 2019

Hi! Welcome to NODE AND EJS TEMPLATE ENGINE SERIES. Today, we will talk about EJS loops, precisely the for loop.

The for loop is very useful and used in several special web applications.

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

You can use either command prompt or PowerShell as terminal.

We will create 2 files as usual, one for our express server file and the second our ejs file.

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

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("home");
});
app.listen(3000, function() {
    console.log("server is listening!!!");
});

Unlike any other express app, we used res.render then the ejs file and not res.send.

Also, I didn't require the ejs app. There's no problem!. You can do so if you wish.

Now, let's create our ejs files:

Open a text editor and type the following code, save as home.ejs

<% for (var i =1; i <=10;  i++ ) { %>
<br/>  <%= i %> 
<%#  will output the numbers 1-10 %>
<% } %>

Your ejs file should be saved in the views folder found in your node project directory.

Take Note, the folder name views is not a random word I selected but it's the reserved folder name where express checks for template engine by default.

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

  • The code above will output an increment of 1-10.
  • You can see the different type of tags used in each case.
  • You can equally see how comments are written in EJS using the tag:
        <%#  comments here! %>
    

Output

for loops in EJS

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.