Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional class for html using pure handlebars

I'm using handlebars to render code in server side (no angular/ember)

Can I still somehow have something like:
<p dir="auto" {{#if isRTL: class=align-right}}>{{{content}}}</p>

I want to have a CSS class only if a bolean is true Something similar to ember's bind-attr...

Without it the code is a mess:

{{#if isRTL}}
    <p dir="auto" class="align-right>{{{content}}}</p>
{{else}}
    <p dir="auto">{{{content}}}</p>
{{#if}}
like image 659
Boaz Avatar asked Jul 04 '15 15:07

Boaz


2 Answers

It is not necessary to wrap around entire HTML elements. You can just wrap the class with the if clause.

<p dir="auto" {{#if isRTL}}class="align-right"{{/if}}>{{{content}}}</p>

This will render the class="align-right" attribute only if isRTL is truthy.

Also, as Handlebars is an extension of Mustache you could use:

<p dir="auto" {{#isRTL}}class="align-right"{{/isRTL}}>{{{content}}}</p>
like image 69
dreyescat Avatar answered Nov 04 '22 11:11

dreyescat


With a helper i achieved clean. But in my case condition was two variables truthiness.

//js
Handlebars.registerHelper('ternary', function(cond, v1, v2) {
   return cond ? v1 : v2;
});


//html
<p dir="auto" class="some-other-class {{ternary isRTL 'align-right' 'align-left'}}">{{{content}}}</p>
like image 43
Priya Avatar answered Nov 04 '22 12:11

Priya