哈希数组上的 Handlebars JS

Handlebars JS on Array of Hashes

我是 Handlebars JS 的新手,只是想了解它们。 我正在尝试在包含哈希数组的数据上实现把手。 这是我的脚本:-

<div id="test"></div>

<script id="template" type="text/x-handlebars-template"> 
    <h1>{{title}}</h1>
    <h2>{{body}}</h2>
</script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
<script>

 $(document).ready(function (){

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

     var context  = [{title: "ABC",body: "DEF"},{title: "GHI",body:"JKL"}];

     console.log(context);
     var ht = template(context);
     console.log(ht);
     $("#test").html(ht);
 });

</script>

输出没有显示任何内容 如何使用 handlebars 模板访问哈希数组。上面脚本中的ex变量context。 我们可以只在散列上使用车把吗?

谁能给我解释一下。

谢谢

您可以使用 {{#each}} 助手遍历集合。在您的情况下,它将是这样的:

{{#each this}}
  <h1>{{title}}</h1>
  <h2>{{body}}</h2>
{{/each}} 

当然我们只能在散列上使用它 - 试试吧。 您可能会发现阅读这篇文章很有用:http://handlebarsjs.com/builtin_helpers.html

我希望你的脚本标签看起来不像你的 post 并且它实际上不缺少 "http" 部分

<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>