Raja G
Raja G

Reputation: 6643

JavaScript: Adding if condition inside of a template variable

I have a template variable in Javascript as below

 var TABLE_ROW = '<tr class={{bgColor}}>'
            + '<td><input id={{ID}} type="checkbox" class="mysqlListCheckbox" checked="checked"/> <span style="padding: 7px;">{{COUNT}}</span></td>'
    + '<td><p class=text-warning>{{COMMENTS}}</p></td>'
    + '</tr>';

At this moment ID is always checked but I want to modify it such as ID should not be checked/selected if COMMENTS is empty.

I am new to Javascript template variables. Any reference links to achieve this are highly appreciated.

Thank you.

Upvotes: 0

Views: 319

Answers (2)

RNV
RNV

Reputation: 21

Since you are new to Javascript, please try to understand How JS works. JS as such does not provide any templating out of the box for template purpose you can use HandleBars.js, in case of if you have used HandleBars. I would suggest you to use a helper function to handle this.

Link for handlebars https://handlebarsjs.com/

Handlebars.registerHelper('decideSelect',function(param){
    if(param.COMMENTS.length==0){
        let Htmlstr =  '<td><input id='+param.ID+' type="checkbox" class="mysqlListCheckbox" /> <span style="padding: 7px;">'+param.COUNT+'</span></td>'+'<td><p class=text-warning>'+param.COMMENTS+'</p></td>';
        return Htmlstr;
    }else{
        let Htmlstr =  '<td><input id='+param.ID+' type="checkbox" class="mysqlListCheckbox" checked="checked"/> <span style="padding: 7px;">'+param.COUNT+'</span></td>'+'<td><p class=text-warning>'+param.COMMENTS+'</p></td>';
        return Htmlstr;
    }


});
};

var TABLE_ROW = '<tr class={{bgColor}}>'
    + '{{decideSelect this}}</tr>';

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44105

Use a ternary operator (if the templating engine supports it):

var TABLE_ROW = '<tr class={{bgColor}}>'
            + '<td><input id={{ID}} type="checkbox" class="mysqlListCheckbox" checked={{COMMENTS == "" ? "" : "checked"}}/> <span style="padding: 7px;">{{COUNT}}</span></td>'
    + '<td><p class=text-warning>{{COMMENTS}}</p></td>'
    + '</tr>';

Upvotes: 1

Related Questions