简体   繁体   中英

How to pass a JSON object to EJS javascript loop?

Need some help here, i am trying to pass a Json object as myVar to the below home.ejs file. How should i assign the value to the variable called data ?

<table id="example" class="table table-striped table-bordered dataTable" cellspacing="0" width="100%">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">CSI ID</th>
      <th scope="col">App Name</th>
      <th scope="col">Status</th>
    </tr>
  </thead>
  <tbody>
    <!-- Below throws the error -->
    <% var data = <%= myVar %>
  <% for (var i = 0; i < data.length; i++) { %>
    <tr>
      <td><%= data[i].id %></td>
      <td><%= data[i].name %></td>
    </tr>    
  <% } %>
  </tbody>
</table>

Error Message

Could not find matching close tag for "<%".> 

app.js

Here "projects" outputs JSON Data

  app.get("/",function(req,resp) { 

    client.projects.getAll()
  .then(function(projects){
    console.log(projects); //buildList.build is an array of builds, from most recent to the count parameter
   myJsonData = projects;

  });
 resp.render('nav', {"page":"home.ejs","myVar":myJsonData});
  });

res.render accept the view name to render and an optional parameter that is an object containing local variables for the view. that's mean if the second parameter is an object like this { name: "value"} then you can access variable name from ejs view. your code should be:

Route handler:

app.get("/",function(req,resp) { 

    client.projects.getAll().then( function(projects) {

        // render response when you get projects populated
        resp.render('nav', { page: "home.ejs", data: projects });

    });

});

View:

<table id="example" class="table table-striped table-bordered dataTable" cellspacing="0" width="100%">
    <thead>
        <tr>
        <th scope="col">#</th>
        <th scope="col">CSI ID</th>
        <th scope="col">App Name</th>
        <th scope="col">Status</th>
        </tr>
    </thead>
    <tbody>
        <!-- get projects array from the data property -->
        <% for (var i = 0; i < data.length; i++) { %>
            <tr>
                <td><%= data[i].id %></td>
                <td><%= data[i].name %></td>
            </tr>    
        <% } %>
    </tbody>
</table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM