anjanesh
anjanesh

Reputation: 4251

Iterate over a value in a handlebars template

In my JSON object I have an property say i which specifies a loop value.
What I would like to is to iterate it in my HTML template and output that many instances of a character, say "-".
Im trying to achieve something like this :

<td>
for i = 1 to {{i}}: print "-"
{{name}}
</td>

Is this even possible ?
So if the JSON object has like {i:5, name:"John"}
it should output -----John

Upvotes: 1

Views: 217

Answers (1)

s.ermakovich
s.ermakovich

Reputation: 2674

Handlebars doesn't provide anything like this out of the box. However, you can define your own helper for this task:

Handlebars.registerHelper('character', function(character, times) {
  var out = "";

  for(var i=0, times; i<times; ++i) {
    out += character;
  }

  return out;
});

Sample usage:

{{character "-" 5}}{{name}}

Upvotes: 2

Related Questions