handlebars.js - How to define an array and loop in a template? - Stack Overflow

The following is the unsuccessful code{{#each ['Home', 'About']}}<p>{{this}}

The following is the unsuccessful code

{{#each ['Home', 'About']}}
  <p>{{this}}</p>
{{/each}}

I understand that I can define the array in js and pass it to handlebars to have it render successfully. But I want to do this only in the template. Sometimes I just need a super simple loop, like in my example.

I saw some older posts that required registering a helper but can't the built-in helper #with / #each do that?

The following is the unsuccessful code

{{#each ['Home', 'About']}}
  <p>{{this}}</p>
{{/each}}

I understand that I can define the array in js and pass it to handlebars to have it render successfully. But I want to do this only in the template. Sometimes I just need a super simple loop, like in my example.

I saw some older posts that required registering a helper but can't the built-in helper #with / #each do that?

Share Improve this question edited Mar 10 at 14:37 DarkBee 15.5k8 gold badges72 silver badges118 bronze badges asked Mar 10 at 14:24 aboutjqueryaboutjquery 9402 gold badges11 silver badges23 bronze badges 1
  • According to this thread it seems that inline arrays are not a thing in Handlebars - Unsure if you are using ember.js, if so than this answer could help – DarkBee Commented Mar 10 at 14:37
Add a comment  | 

1 Answer 1

Reset to default 0

Handlebars doesn't parse JavaScript expressions or inline literals (like [], +, &&)...it will not accept JavaScript-like expressions. You must register a helper like this in your server.js:

app.engine(
  "handlebars",
  engine({
    helpers: {
      array: (...args) => args.slice(0, -1),
    },
  })
);

then call it from your #each loop like:

{{#each (array 'Home' 'About')}}
  <p>{{this}}</p>
{{/each}}

OR pass the array from directly your route like this:

res.render('template', { myArray: ['Home', 'About']});

and call it it your #each loop like this:

{{#each myArray}}
  <p>{{this}}</p>
{{/each}}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744842124a4596620.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信