使用模板(Jade)创建一个表并动态填充它

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

本文关键字:一个 动态 填充 创建 Jade      更新时间:2023-09-26

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

我用html:创建了一个简单的表格

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

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

$.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");
    }
});

我为创建表而注入的代码非常糟糕。一个朋友告诉我应该使用模板。所以我看了看,我创造了一个玉石模板。

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

现在,我的问题是:如何以"美丽的方式"填充表格?我必须调用一个javascript文件来进行ajax查询,但是,如何在不传递不可读的丑陋html字符串的情况下填充表呢?

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

它需要基于JS:

  • Undercore
  • 嵌入式
  • Mustache

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

我个人的建议是:

  • Twig
  • 板材