Handlebar - dynamic element attributes

handlebars.js, mustache

Solution

Handlebars only gave you `{{#if}}` helper (which can be use here, it's just verbose). Being logic less, it doesn't evaluate code passed inside the brackets (Underscore templates does this).

This is a good thing as it make sure your template won't have any side effects.

Here you'll probably want to remove this logic from the template and pass the class name as a template argument:

template({ genderClass: user.female ? 'female-span' : 'male-span' });

Then, in the template:

<span class="{{genderClass}}">{{name}}</span>

In your case you're in an array, so you could just add `genderClass` as a model property. Otherwise you could use a custom helper method, but that's a lot of overhead for something quite simple.

Problem

I want to do something like this: ``` {{#each user}} <span class="{{user.female ? 'female-span' : 'male-span'}}">{{name}}</span> {{/each}} ``` This is easily doable in something like angularjs but I cannot do this handlebar. What is the idiom/pattern to follow in handlebar when I want to dynamically change element attributes? Are there any handlebar plugins that do this?

Original source