Dynamically set CSS property based on template value

Is it possible to dynamically set the text color of the input field based on the value of the handlebars.js template?

I initially create my html using this template:

<div class="board"> <div class="header"> <span class="name">Project</span> <span class="status">Status</span> </div> {{#each projects}} {{> project}} {{/each}} </div> 

Where projects is an object read from db. The resulting html (what is displayed on the page, and not what is in my html) for each project looks something like this:

 <div class="project"> <span class="name">FOO</span> <span class="status">OK</span> </div> <div class="project"> <span class="name">BAR</span> <span class="status">NOTOK</span> </div> 

I would like this html to display the text color OK and NOTOK dynamically.

I already have a handlebars helper function that will successfully return the correct color code based on each option, and I can call this using:

 {{getStatusColor currentStatus}} 

What I would like to do is put this function call directly in css itself, a bit like:

 font-color: {{getStatusColor currentStatus}} 

But obviously this will not work. This function really looks like the right approach, but where can I use it to correctly format the text on the page?

+7
source share
1 answer

Answering my own question: the template needs to be expanded (from {{> projects}} ) to allow conditional rendering.

 <div class="board"> <div class="header"> <span class="name">Project</span> <span class="status">Status</span> </div> {{#each projects}} <div class="project"> <span class="name">{{name}}</span> <span class="status" style="color:{{getStatusColor status}}">{{status}}</span> </div> {{/each}} </div> 

For completeness, the getStatusColor helper function looks like this:

 Handlebars.registerHelper('getStatusColor', function(status) { switch (status) { case "GOOD" : { return 'green'; } break; case "BAD" : { return 'red'; } break; default : { ...etc.; } }); 

UPDATE: In the interest of honesty, I must admit that I completely missed that I already had this extended template in my code and that {{> projects}} pointed to this. I should just add the style="color:{{getStatusColor status}}" attribute directly to the project reference template. So, for me, as for others, the final, working, HTML:

 <template name="foo"> <div class="board"> <div class="header"> <span class="name">Project</span> <span class="status">Status</span> </div> {{#each projects}} {{> project}} {{/each}} </div> </template> <template name="project"> <div class="project {{selected}}"> <span class="name">{{name}}</span> <span class="status"style="color:{{getStatusColor status}}">{{status}}</span> </div> </template> 
+15
source

All Articles