Search code examples
handlebars.js

Comma Separate String using handlebars.js


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


Solution

  • 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).