简体   繁体   中英

handlebars.js - difference between #each block and #block

What's the difference between these two handlebars.js templates?

{{#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. 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. this becomes the each elements in that iterations.

Similarly in the first example myblock becomes a helper since it follows the # sign.

{{#myblock}}

  {{this}}

{{/myblock}}

Now since there is no predefined helper with name myblock, you can create the custom helper using Handlebars.registerHelper() like following.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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