简体   繁体   English

如何将JSON对象传递给EJS javascript循环?

[英]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. 在这里需要一些帮助,我正在尝试将Json对象作为myVar传递到下面的home.ejs文件。 How should i assign the value to the variable called data ? 我应该如何将值分配给名为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 app.js

Here "projects" outputs JSON Data 这里的“项目”输出JSON数据

  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. res.render接受要呈现的视图名称和一个可选参数,该参数是一个包含视图局部变量的对象。 that's mean if the second parameter is an object like this { name: "value"} then you can access variable name from ejs view. 这意味着如果第二个参数是这样的对象{ name: "value"}那么您可以从ejs视图访问变量name 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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