简体   繁体   中英

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?

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM