Michael Joseph Aubry
Michael Joseph Aubry

Reputation: 13402

Handlebars variables for cleaner templates (handlebars.js)?

So some code like this can make my html look ugly and confusing.

{{#if user.facebook.id}} 
    <img class="img-rounded" src="https://graph.facebook.com/{{user.facebook.id}}/picture"/>
{{else}} 
    <img class="img-rounded" src="http://www.gravatar.com/avatar/{{user.local.gravatar}}?s=50"/> 
{{/if}}

In javascript I could

var picture;

if(user.facebook.id) {
     picture = '<img class="img-rounded" src="https://graph.facebook.com/'+user.facebook.id+'/picture"/>';
} else {
     picture = '<img class="img-rounded" src="http://www.gravatar.com/avatar/'+user.local.gravitar+'?s=50"/>';
}

return picture;

You know something like that and then call picture and it will know what to do. Is there a way to do something like this in handlebars. I used to do something like this in underscore.js.

Do I need to create a handlebars helper method, or is there something built in I can leverage?

Upvotes: 0

Views: 202

Answers (1)

ckross01
ckross01

Reputation: 1671

Handlebar helper method is going to be your best bet if you dont like the Html version.

{{checkFacebookId user.facebook.id user.local.gravatar}} 

Handlebars.registerHelper('checkFacebookId', function (id, gravatar) {
    var picture = '';
    if (id) {
         picture = '<img class="img-rounded" src="https://graph.facebook.com/' + id + '/picture"/>';
    } else {
         picture = '<img class="img-rounded" src="http://www.gravatar.com/avatar/' + gravatar + '?s=50"/>';
    }
    return new Handlebars.SafeString(picture);
});

Upvotes: 1

Related Questions