在HandlebarsJS中显示多个数组

时间:2018-01-30 16:08:33

标签: javascript html arrays json handlebars.js

我第一次使用HandlebarsJS,我希望在其中使用多个数组。这可能吗?

我已经设置了Codepen模板,但我很难实现来自2个数组和外部URL的数据。我也用MustacheJS尝试了这个,但我相信只允许一个数组而不是过滤 - 与Handlebars不同

这是external JSONCodePen

<!-- REQUIRED - Display site name, url and title in top section. With product data below using the "other array-->
<script id="myTemplate" type="text/x-handlebars-template">
{{content}}
</script>

<div id="contentArea"></div>

<script>
var data     = {"content": "Hello, World!"};
var source   = $("#myTemplate").html();
var template = Handlebars.compile(source);
var html     = template(data);
$("#contentArea").text(html);
</script>

这是my first template attempt,但目前未能集成JSON数组

1 个答案:

答案 0 :(得分:0)

可以使用{{#each}}块助手。我还注册了我自己的帮助器{{{s}}},它只是返回它的参数JSON.stringify()',所以我可以打印这些数组。如何获取它们是另一个问题,我复制&amp;为了简单起见,将粘贴到代码的Javascript部分。另外,这里是JS fiddle

var data = {"content": "Hello, World!", "multipleArrays": [
  [
    {
      "productimage": "https://c.static-nike.com/a/images/t_PDP_864_v1/f_auto/i0lfddlghaiwfqlvlqay/air-vortex-shoe-fmq6pS.jpg",
      "producturl": "https://www.nike.com/gb/t/air-vortex-shoe-fmq6pS"
    },
    {
      "productimage": "https://c.static-nike.com/a/images/t_PDP_864_v1/f_auto/cmuof8adhfipkvd0f43r/air-max-95-shoe-XPTbV2mM.jpg",
      "producturl": "https://www.nike.com/gb/t/air-max-95-shoe-XPTbV2mM"
    }
  ],
  [
    {
      "sitename": "Nike",
      "sitetitle": "Nike. Just Do It.. Nike.com",
      "siteurl": "https://www.nike.com/gb/en_gb/"
    }
  ]
]};

Handlebars.registerHelper('s', function(arg) {
  return JSON.stringify(arg);
})
var source = $("#myTemplate").html();
var template = Handlebars.compile(source);
var html = template(data);
$("#contentArea").html(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>
<!-- REQUIRED - Display site name, url and title in top section. With product data below using the "other array-->
<script id="myTemplate" type="text/x-handlebars-template">
  <h1>Content: {{content}}</h1>
  <hr>
    
  <h2>Stringified multiple arrays:</h2> 
  {{{s multipleArrays}}}
  <hr>
    
  {{#each multipleArrays}}
   <h2>Item {{@index}}</h2>
  {{{s this}}}
  <br>
  <br>
  {{/each}}
  
  
</script>

<div id="contentArea">
</div>