What is the proper way to loop through an array in an EJS template after an AJAX Call (using ExpressJS)?
Asked Answered
A

3

21

I am trying to loop through an array of objects that I got from an http call using to my internal API using the request module/package. So far, I am able to get my data back from the API and DISPLAY the full object on my page. I would like to display it on my page and loop through it using the EJS templating system. I know I can use AngularJS for frontend stuff, but I would like to see how far I can go with only server-side.

Below is my code:

server.js

// Prepend /api to my apiRoutes
app.use('/api', require('./app/api'));

api.js

var Report = require('./models/report');
var express  = require('express');
var apiRoutes = express.Router();

apiRoutes.route('/reports', isLoggedIn)  
     .get(function (req, res,next) {
          // use mongoose to get all reports in the database
          Report.find(function (err, reports) {
                 // if there is an error retrieving, send the error.
                 // nothing after res.send(err) will execute
                 if (err)
                    return res.send(err);
                    res.json(reports);
          });
    });

routes.js

var User = require('./models/user');
var request = require('request');
module.exports = function (app, passport) {
    
    app.get('/reports', isLoggedIn, function (req, res) {
        res.render('pages/new-report.ejs', {
            user: req.user,
            title:'New Report'
        });
    });


    request({
        uri:'http://localhost:2016/api/reports',
        method:'GET'
    }).on('data',function(data){
        console.log('decoded chunk:' + data)
    }).on('response',function(resp){
        resp.on('data', function(data){
            console.log('received:' + data.length + ' bytes of compressed data');
            app.get('/timeline', isLoggedIn, function (req, res) {
                res.render('pages/timeline', {
                    user: req.user,
                    title:'Timeline',
                    reports: data
                });
            });
        })
    }); 
}  

reports.ejs
So if I simply output the entire reports object like this <p><%= reports %></p> on my page, everything works fine and I get something like this:

[
  {
    "_id": "5775d396077082280df0fbb1",
    "author": "57582911a2761f9c77f15528",
    "dateTime": "30 June 2016 - 07:18 PM",
    "picture": "",
    "description": "",
    "location": [
      -122.46596999999997,
      37.784495
    ],
    "latitude": 37.784495,
    "longitude": -122.46596999999997,
    "address": "4529 California St, San Francisco, CA 94118, USA",
    "contact": "John Doe",
    "type": "Financial",
    "__v": 0,
    "updated_at": "2016-07-01T02:21:10.259Z",
    "created_at": "2016-07-01T02:21:10.237Z",
    "tags": [
      "tag1,tag2"
    ]
  }
]

But if I try to loop through the object as seen below It get an UNDEFINED as a return property of my report object and I get an infinite loop apparently.

<ul class="timeline">
    <% reports.forEach(function(report) { %>
    <li class="timeline-yellow">
        <div class="timeline-time">
            <span class="date" style="text-align:left">
            <%= report.type %> </span>
            <span class="time" style="font-weight:700;font-size:25px;line-height:20px;text-align:left;">
            <%= report.dateTime %> </span>
        </div>
    </li>
    <% }) %>
</ul>

I have tried another variation of the loop but I am still unsuccessful:

<ul class="timeline">
    <% for (var i = 0; i < reports.length; i++) { %>
    <li class="timeline-yellow">
        <div class="timeline-time">
            <span class="date" style="text-align:left">
            <%= report[i].type %>
            4/10/13 </span>
            <span class="time" style="font-weight:700;font-size:25px;line-height:20px;text-align:left;">
            <%= report[i].dateTime %> </span>
        </div>
    </li>
    <% } %>
</ul>
Abri answered 4/7, 2016 at 7:29 Comment(0)
F
20

The syntax for the for loop in ejs is perfect but the iterated array name is reports and you seem to use report[i] inside the iteration, which needs to be changed as reports[i], which should work.

reports.ejs

<ul class="timeline">
    <% for (var i = 0; i < reports.length; i++) { %>
    <li class="timeline-yellow">
        <div class="timeline-time">
            <span class="date" style="text-align:left">
            <%= reports[i].type %>
            4/10/13 </span>
            <span class="time" style="font-weight:700;font-size:25px;line-height:20px;text-align:left;">
            <%= reports[i].dateTime %> </span>
        </div>
    </li>
    <% } %>
</ul>

Hope this helps.

Fining answered 14/7, 2016 at 10:36 Comment(0)
B
4
I guess something like this .. 

<% if (reports.length > 0){%> // Checking if there are reports
  <ul class="timeline">
      <%  for (let report of reports){ %>
        <li class="timeline-yellow">
          <div class="timeline-time">
            <span class="date" style="text-align:left">
              <%= report.type %> 
               4/10/13 </span>
              <span class="time" style="font-weight:700;font-size:25px;line- 
  height:20px;text-align:left;">
              <%= report.dateTime %> </span>
          </div>
      </li>
      <% } %>
  </ul>
 <%}%>
<%}%>
Backhouse answered 1/3, 2019 at 20:48 Comment(2)
Please explain your answerMillionaire
Basically he sends as a respons an array named reports. EJS lets you write with JavaScript - The best is to look here : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Backhouse
O
0

Here is my working version using loopback3 and ejs:

In server/boot/routes.js:

module.exports = function(app) {
  const router = app.loopback.Router();

  router.get('/', function(req, res){
    app.models.ZenGarden.find()
        .then(plants => {
          console.log('plants: ', plants)
          res.render('index', {plants:plants})
        }).catch(err => {
          console.log('Failed to find in ZenGarden: ', err)
          res.render('index')
        })
  });

  router.post('/', function(req, res){
    var plants = req.body.plants;
    if (plants) {
      for (var i = 0; i < plants.length; i++) {
        console.log(plants[i])
        app.models.ZenGarden.upsert(plants[i])
            .then().catch(err => console.log(err))
      }
    }
    return res.render('index', {plants:plants})
  })

  app.use(router);
};

In server/views/index.ejs:

<div>
    <form action='/' method='POST'>
        <% if (plants) { %>
            <table>
                <tr><td>Name</td><td>Count</td></tr>
                <% for (var i = 0; i < plants.length; i++) { %>
                    <tr>
                        <input type='hidden' value=<%= plants[i].id %> name='plants[<%= i %>][id]'>
                        <input type='hidden' value="<%= plants[i].name %>" name='plants[<%= i %>][name]'>
                        <td><%= plants[i].name %></td>
                        <td><input type='text' value=<%= plants[i].count %> name='plants[<%= i%>][count]'</td></tr>
                <% } %>
            </table>
            <button type='submit'>Save</button>
        <% } else { %>
            <p>No plant in Zen Garden :-(</p>
        <% } %>
    </form>
</div>

Make sure to add the following in server/server.js:

const path = require('path')
const bodyparser = require('body-parser')

app.set('view engine', 'ejs')
app.set('views', path.resolve(__dirname, 'views'))

app.middleware('initial', bodyparser.urlencoded({extended:true}))
app.middleware('initial', bodyparser.json())

Here is the definition of the model ZenGarden(common/models/zen-garden.json):

{
  "name": "ZenGarden",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string",
      "required": true
    },
    "count": {
      "type": "number",
      "required": true
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}
Okelley answered 2/2, 2021 at 22:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.