9

These days working i am working with handlerbars.js and it seems pretty interesting. In there i need a small help from you guys.

i have a following json input

"ALERTS": [
    {
        "alert_description": "ALCOHOL",
    },
    {
        "alert_description": "DIAGNOSIS",
    }
]

and i need to write a template to create following comma separated string.

ALCOHOL, DIAGNOSIS

i was able to print these values using line by line using following template.

<div>
   <div>
{{#each this}}
    <span>{{alert_description}}</span>
{{/each}}
</div>
</div>

can you guys please help me to solve this issue? appreciate your help

Thanks Keth

2 Answers 2

7

You can do this without writing a helper by using {{#each}} and testing the implicit @index variable:

{{#each this}}
    {{#if @index}}, {{/if}}
    <span>{{alert_description}}</span>
{{/each}}

You can also test @first and @last (see handlebarsjs docs).

Sign up to request clarification or add additional context in comments.

Comments

3

For this kind of scenario, I will create a helper.

Here is my implementation

Handlebars.registerHelper('commalist', function(items, options) {
  var out = '';

  for(var i=0, l=items.length; i<l; i++) {
    out = out + options.fn(items[i]) + (i!==(l-1) ? ",":"");
  }
  return out;
});

and the template

<div>
   <div>
    {{#commalist this}}
       <span>{{alert_description}}</span>
    {{/commalist}}
   </div>
</div>

In fact, the helper is here only for comma. You can still put html inside the helper (span, div, ...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.