使用Mustache.Js模板将嵌套数组绑定到HTML页面

时间:2017-12-03 11:10:44

标签: javascript jquery mustache

如何使用Mustache.js将下面的JSON数据绑定到Html页面?

数据 -

[
    {
        "procedureList": [
            {
                "procedureName": "Root Canal",
                "cost": 10200
            }
        ],
        "department": "Dental"
    },
    {
        "procedureList": [
            {
                "procedureName": "Vasactomy",
                "cost": 10000
            },
            {
                "procedureName": "IVF",
                "cost": 10000
            }
        ],
        "department": "Gynic"
    },
]

我尝试了下面的解决方案,但它只为部门'Dental'创建数据。它不会遍历整个Json数组。

任何帮助纠正以下模板都将非常感激

            <div class="panel-group" id="accordion">            
               {{#department}} <!--array of department names-->
                 <div class="panel panel-default">
                    <div class="panel-heading">
                       <h4 class="panel-title">
                          <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne"><span class="glyphicon glyphicon-plus"></span>&nbsp;&nbsp;{{{department}}}</a>
                       </h4>
                    </div>
                    <div id="collapseOne" class="panel-collapse collapse">
                       <div class="panel-body">                        
                          {{#procedureList}} <!--array of procedure names-->
                          <div class="row">
                             <div class="col-md-6">
                                <p><a href="" target="_blank">{{procedureName}}</a></p>
                             </div>
                             <div class="col-md-6"> 
                                <button type = "button" class = "btn btn-primary">Starts from {{cost}}</button>                                 
                             </div>
                          </div>
                          <p></p>
                          {{/procedureList}} <!--array of procedure names-->                                                         
                       </div>
                    </div>
                 </div>
                 {{/department}} <!--Array of department names-->                   
              </div>

1 个答案:

答案 0 :(得分:1)

问题是你的json没有一个名为departments的密钥,其中是一系列部门。它直接是一个数组。

您可以将json更改为

{ "departments" : [<your existing json>]}

或使用#./.来循环,如果原始元素是数组。

<div class="panel-group" id="accordion">
  {{#.}}<!--array of department names-->
  <...snip...>
  {{/.}}<!--Array of department names-->
</div>