车把通过占位符中的索引访问嵌套的数组值

时间:2018-11-01 15:54:33

标签: handlebars.js

我只是从handlebars.js开始呈现以下json,但是我不确定如何使用索引访问嵌套json数组的值。

enter image description here

以下是模板,我尝试使用{{this.1}}<div>{{name}}<div> {{#each params}}<div> <span>{{this.1}}</span> <input type="checkbox" name="opt_{{../id}}[]" value="{{this.0}}"> </div>{{/each}} </div></div> ,但没有运气

{
    "id": 5753,
    "name": "Состав съемщиков",
    "params": [
      [15868, "Семья"],
      [15911, "Женщина"],
      [15913, "Мужчина"]
    ]
  }

以下是JSON字符串,以防万一:

{{1}}

2 个答案:

答案 0 :(得分:0)

您可以调整JSON对象吗?如果可以,请尝试以下操作:

HTML正文:

  <h1>Handlebars JS Example</h1>
    <script id="some-template" type="text/x-handlebars-template"> 
    <div>
      {{this.name}}
      <div>
        {{#each this.params}}
        <div>
          <span>{{this.txt}}</span>
          <input type="checkbox" name="opt_{{../id}}[]" value="{{this.id}}">
        </div>
       {{/each}}
      </div>
   </div>
   </script>

index.js

var source = $("#some-template").html(); 
var template = Handlebars.compile(source); 

var data = {
    "id": 5753,
    "name": "Состав съемщиков",
    "params": [
      {"id": "15868", "txt":"Семья"},
      {"id": "15911", "txt":"Женщина"},
      {"id": "15913", "txt":"Мужчина"}
    ]
}

$('body').append(template(data));

结果:

Handlebars JS Example
Состав съемщиков
<!-- these are checkboxes but I can't insert a picture.. -->
Семья  
Женщина  
Мужчина

我相信这是由于您的JSON对象格式,下面是我刚刚概述的解决方案的实时示例:

var source = $("#some-template").html(); 
var template = Handlebars.compile(source); 

var data = {
    "id": 5753,
    "name": "Состав съемщиков",
    "params": [
      {"id": "15868", "txt":"Семья"},
      {"id": "15911", "txt":"Женщина"},
      {"id": "15913", "txt":"Мужчина"}
    ]
  }

$('body').append(template(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.12/handlebars.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Handlebars JS Example</h1>
<script id="some-template" type="text/x-handlebars-template"> 
<div>{{this.name}}<div>
    {{#each this.params}}<div>
        <span>{{this.txt}}</span>
        <input type="checkbox" name="opt_{{../id}}[]" value="{{this.id}}">
    </div>{{/each}}
</div></div>
</script>

希望这会有所帮助:)

答案 1 :(得分:0)

使用数组索引的语法在方括号[0]中,这是我的工作模板:

<div>{{this.name}}<div>
    {{#each this.params}}<div>
        <span>{{this.[1]}}</span>
        <input type="checkbox" name="opt_{{../id}}[]" value="{{this.[0]}}">
    </div>{{/each}}
</div></div>