Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/447.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript handlebar.js#每个数组。使用第一项作为标题?_Javascript_Handlebars.js - Fatal编程技术网

Javascript handlebar.js#每个数组。使用第一项作为标题?

Javascript handlebar.js#每个数组。使用第一项作为标题?,javascript,handlebars.js,Javascript,Handlebars.js,我有以下数据: var test = []; test.push({typ: 'a', name="bur"}); test.push({typ: 'a', name="fur"}); test.push({typ: 'b', name="kok"}); test.push({typ: 'b', name="bur"}); 我用handlebar.js呈现它,并在此模板中使用它: {{#each .}} <div> <div>{{ name }}</div

我有以下数据:

var test = [];
test.push({typ: 'a', name="bur"});
test.push({typ: 'a', name="fur"});
test.push({typ: 'b', name="kok"});
test.push({typ: 'b', name="bur"});
我用handlebar.js呈现它,并在此模板中使用它:

{{#each .}}
  <div>
  <div>{{ name }}</div>
  </div> 
{{/each}}
{{{#each.}
{{name}}
{{/每个}}
这很好,但我想把“typ”作为标题,如下所示:

<div class="head">a</div>
<div class="name">bur</div>
<div class="name">fur</div>
<div class="head">b</div>
<div class="name">kok</div>
<div class="name">bur</div>
a
伯尔
毛皮
B
角
伯尔

但是我该怎么做呢?

这不是一个直接的答案,但我认为这样设置CSS会更干净:

div {
  /* Header style */
}

div ~ div {
  /* normal style */
}
把手解决方案是在循环内使用特殊值
{{@index}
(或对象的
@key
)来访问索引并相应地设置样式。(但这是一个很大的开销,因为把手的逻辑性很低,所以您可能需要创建一个helper
ifEqual0
或类似的东西……)


使用把手时,更简洁的方法是将数组作为
标题和
项分开,并将其作为参数传递给模板。

为什么不变换对象并按以下方式执行:

JS:

模板:

{{#each .}}
     <div class="head">{{ @key }}</div>
     {{#each .}}
          <div class="name">{{ this }}</div>
     {{/each}}
{{/each}}
{{{#each.}
{{@key}}
{{{#每个。}
{{this}}
{{/每个}}
{{/每个}}

您不能在handlebar中执行太多操作(尽管您有handlebar帮助器并添加了自己的帮助器)。我建议你试着调整你的模态和模板,并且主要是以一种方式

{{#each .}}
     <div class="head">{{ @key }}</div>
     {{#each .}}
          <div class="name">{{ this }}</div>
     {{/each}}
{{/each}}