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

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


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.


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> <%}%><%}%>


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": {}}