使用模板 (Jade) 创建 table 并动态填充它

Using a template (Jade) to create a table and populate it dynamically

我对在 html 中构建一个简单的 table 并动态填充它感到困惑。

我在 html 中创建了一个简单的 table :

<div class="container" style="width:100%;padding:50px">
    <table id="tblItems" class="table table-striped">
      <thead>
      <tr>
        <th>Id</th>
        <th>Action</th>
        <th>Objet</th>
        <th>Champs</th>
        <th>Demandeur</th>
        <th>Status</th>
        <th>Date de la prise en compte</th>
        <th>Actions</th>
      </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
  </div>

然后为了填充我的 table,我发出 ajax 请求来检索数据以填充 table :

$.ajax({
        type: "GET",
        url: "http://localhost:3000/suggestions?limit=5&offset=" + offset,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            $.each(response, function(){
                var data = JSON.parse(this.fields);

                ... DOING OTHER STUFF    

                //THIS LOOKS HORRIBLE!! (adding content to my table)
                rows += "<tr><td>" + this.id + "</td><td>" + this.action + "</td><td>" + this.entity + "</td><td style='color:green'>" + fields
                + "</td><td>" + this.requester +  "</td><td>" + this.is_approved + "</td><td>" + this.creation_date +  "</td><td>" + images + "</td></tr>";
            });
          $(rows).appendTo("#tblItems tbody");
    failure: function () {
        console.log("fail");
        $("#tblItems").append(" Error when fetching data please contact administrator");
    }
});

我为创建 table 而注入的代码太可怕了。 一位朋友告诉我,我应该使用模板。所以我看了看,然后创建了一个玉模板。

doctype
html( lang="en" )
  head
    title Baking Bootstrap Snippets with Jade
    meta( charset='utf-8' )
    meta( http-equiv='X-UA-Compatible', content='IE=edge' )
    meta( name='viewport', content='width=device-width, initial-scale=1.0' )
    meta( name='description', content='Baking Bootstrap Snippets with Jade' )
    //- Bootswatch Theme
    link(href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.0/flatly/bootstrap.min.css", rel="stylesheet")
  body(style="padding-bottom:10rem;")
    .container
    script( src='//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js' )
    script( src='//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js' )
    script( src='script.js' )
    #container(style='padding:50px;')
      table(id="table",class="table table-striped")
      thead
        tr
          th Id
          th Action
          th Objet
          th Champs
          th Demandeur
          th Status
          th Date de la prise en compte
          th Actions
      tbody

现在,我的问题如下:如何在 "beautiful way" 中填充我的 table?我必须调用一个 javascript 文件来进行我的 ajax 查询,但是,我怎样才能填充 table 而不必传递丑陋的 html 字符串不可读?

据我所知,你不能在 jade 中做到这一点,你只需要某种模板引擎。

需要基于JS:

  • 下划线
  • 嵌入式
  • 小胡子

PHP还有另一种方法。将 JSON 解析为 php,然后生成内容。您也可以为此使用一些模板引擎。 (当 PHP 是一个时,有些人会不同意您需要模板引擎)

我个人的建议是:

  • 树枝
  • 盘子