admin管理员组

文章数量:1404567

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}}

本文标签: handlebarsjsHow to define an array and loop in a templateStack Overflow