【问题标题】:How to pass a JSON object to EJS javascript loop?如何将 JSON 对象传递给 EJS javascript 循环?
【发布时间】:2018-02-08 00:24:19
【问题描述】:

这里需要一些帮助,我正在尝试将 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});
  });

【问题讨论】:

    标签: javascript json node.js express callback


    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 2016-11-08
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-26
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多