Reputation: 606
I loop with a handlebars #each through objets with a given boolean property like:
elements: [
{
text: "a"
active: true
},
{
text: "b"
active: false
}
]
What is the simplest way to add a class to an html element based on that property? Something like this:
{{#each elements}}
<article class={{if active 'active-class'}}>
...
{{/each}}
I'm using handlebars 4.0.6
Upvotes: 7
Views: 15332
Reputation: 630
You need to start by opening up a helper block:
{{#if}}
Then, you add the argument you're checking against (in this case a boolean):
{{#if active}}
Then, you close it like this:
{{#if active}}{{/if}}
Then, the content you want to render if the condition is met goes in-between the curly braces:
{{#if active}}text{{/if}}>
So, your HTML would look something like:
{{#each elements}}
<article {{#if active}}class="active"{{/if}}>
...
{{/each}}
Or, if you also want a static class within that element you could do:
{{#each elements}}
<article class="example {{#if active}}active{{/if}}">
...
{{/each}}
Upvotes: 14