递归JSON句柄

时间:2017-09-26 13:01:17

标签: javascript jquery json handlebars.js handlebarshelper

我想用递归JSON做一个把手模板,但我不知道JSON的键是什么(可以改变),我还需要一个IF语句,一个正在工作。有没有办法创建一个Helper来做到这一点?现在我的答案是[对象]。这是我的jsfiddle https://jsfiddle.net/deherinu/dvn4076h/

我的JSON:

var json={
"results": [
 {
   "collection": "employer",
   "summary":{
     "person": [
       { "name": "My name" },
       { "lastname": "My lastname" },
       { "address": "Street" }
     ],
     "job": "CEO"
   }
 },
 {
   "collection": "employer",
   "summary":{
     "person": [
       { "name": "My name" },
       { "lastname": "My lastname" },
       { "address": "Street" }
     ],
     "job": "Administrator"
   }
 },
 {
   "collection": "company",
   "summary": "Company1"
 },
 {
   "collection": "company",
   "summary": "Company2"
 }
   ]
 };

My output

谢谢!

1 个答案:

答案 0 :(得分:0)

将您的内容包裹在person对象周围。

<script id="template" type="text/x-handlebars-template">
  <div style="width: 80%; margin: 0 auto;">
    {{#results}}
    <h3 style="text-transform: uppercase;">{{collection}}</h3>
    {{#xif " collection == 'employer' " }}
    {{#summary}}
    {{#person}}
    <div>
      <table>
        <tbody>
          {{#each this}}
          <tr>
            <td><b>{{@key}}</b></td>
            <td>{{this}}</td>
          </tr>
          {{/each}}
        </tbody>
      </table>
    </div>
    {{/person}}
    {{/summary}}
    {{else}}
    <div>
      {{summary}}
    </div>
    {{/xif}}
    {{/results}}
  </div>
</script>