Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 527
keth Avatar asked May 14 '13 04:05

keth


People also ask

Can you use JavaScript in handlebars?

Handlebars doesn't allow you to write JavaScript directly within templates. Instead, it gives you helpers. These are JavaScript functions that you can call from your templates, and help you reuse code and create complex templates. To call a helper, just use it as an expression - {{helpername}} .

What does handlebars do in JS?

Handlebars. js is a Javascript library used to create reusable webpage templates. The templates are combination of HTML, text, and expressions. The expressions are included in the html document and surrounded by double curly braces.

Does handlebars escape HTML?

HTML Escaping Because it was originally designed to generate HTML, Handlebars escapes values returned by a {{expression}} .

What are helpers in handlebars?

Helpers can be used to implement functionality that is not part of the Handlebars language itself. A helper can be registered at runtime via Handlebars. registerHelper , for example in order to uppercase all characters of a string.


1 Answers

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

like image 89
David Tinker Avatar answered Sep 29 '22 11:09

David Tinker