Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebar - dynamic element attributes

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?

like image 618
pathikrit Avatar asked Aug 20 '13 17:08

pathikrit


1 Answers

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.

like image 181
Simon Boudrias Avatar answered Oct 06 '22 04:10

Simon Boudrias