简体   繁体   English

handlebars.js-#each块和#block之间的区别

[英]handlebars.js - difference between #each block and #block

What's the difference between these two handlebars.js templates? 这两个handlebars.js模板之间有什么区别?

{{#myblock}}

  {{this}}

{{/myblock}}

and

{{#each myblock}}

  {{this}}

{{/each}}

Given that there is no helper defined for "myblock", the two templates (from what I can see) operate and output the same. 鉴于没有为“ myblock”定义帮助程序,因此这两个模板(从我看到的内容)可以操作并输出相同的模板。 Is there any difference between the two templates besides readability? 除了可读性之外,这两个模板之间是否还有其他区别?

The easier way to understand this is whatever that comes after the hash sign (#) is a helper. 理解这一点的更简单方法是使用井号(#)作为帮助器之后的内容。 A helper is function which handlebars calls with the optional paramaters which are derived from what follows the helper declaration in template. 助手是一个函数,它处理带有可选参数的调用,这些参数是从模板中的助手声明之后得出的。

{{#each myblock}}

  {{this}}

{{/each}}

In case of #each it calls the functions which iterates over the argument provided 'myblock' in this case (which will be array in almost all cases) and will output the content generated for each element. 在#each的情况下,它调用对在这种情况下'myblock'提供的参数进行迭代的函数(几乎在所有情况下都是数组),并将输出为每个元素生成的内容。 this becomes the each elements in that iterations. 成为该迭代中的每个元素。

Similarly in the first example myblock becomes a helper since it follows the # sign. 类似地,在第一个示例中,由于myblock跟随#号,因此它成为了一个助手。

{{#myblock}}

  {{this}}

{{/myblock}}

Now since there is no predefined helper with name myblock, you can create the custom helper using Handlebars.registerHelper() like following. 现在,由于没有名称为myblock的预定义帮助程序,您可以使用Handlebars.registerHelper()创建自定义帮助程序,如下所示。

Handlebars.registerHelper('myblock', function(context, options) {
  return options.fn(context);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM