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

时间:2018-02-08 00:24:20

标签: javascript json node.js express callback

在这里需要一些帮助,我试图将一个Json对象作为myVar传递给下面的home.ejs文件。我应该如何将值分配给名为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>
  

错误消息

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

app.js

这里“项目”输出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});
  });

1 个答案:

答案 0 :(得分:1)

res.render接受要渲染的视图名称和可选参数,该参数是包含视图局部变量的对象。这意味着如果第二个参数是像{ name: "value"}这样的对象,那么您可以从ejs视图访问变量name。你的代码应该是:

路线处理程序:

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 });

    });

});

查看:

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