问题
i want to use if then else in hbs file, if {{NumLikes}} is greater than 0 then 1st image else 2nd image, so how i can use if then else in hbs template file using backbone.js.
I am using handelsbar for template.
<div>
< div class="comm-tab-row">
<div class="post-left-panel">
<div class="post-image-container">
<img src="{{UserImageURL}}" alt="" class="post-image" /></br>
<% if ({{NumLikes}} = 0) { %>
<img src="images/myCommunity/like@2x.png" width="20" height="19" id="like-btn" name = "like-Button" >
<% } else { %>
<img src="images/myCommunity/liked@2x.png" width="20" height="19" id="like-btn" name = "like-Button" >
<% } %>
({{NumLikes}})
</div>
</div>
<div class="post-body">
<h5 class="comm-tab-heading">
<span class="navigate-screen" id="{{Id}}" style="text-decoration:underline;">
{{UserName}}
</span>
<span>
-
</span>
<span>
{{format_date Time ""}}
</span>
</h5>
{{Message}}
</div>
<div class="comm-right-panel">
<a href="javascript:void(0);" class="btn-follow" name = "follow-button">FOLLOW</a>
<a href="javascript:void(0);" class="btn-comment" name = "comment-button">{{NumComments}} - COMMENT</a>
</div>
</div>
</div>
</div>
回答1:
You don't need a custom helper for this, the standard {{#if}} will do the right thing with a zero. For example, this template:
<script id="t" type="text/x-handlebars">
{{#if a}}a{{else}}!a{{/if}}<br>
{{#if b}}b{{else}}!b{{/if}}<br>
</script>
and this code:
var t = Handlebars.compile($('#t').html());
$('body').append(t({
a: 0,
b: 1
}));
will give you !a and b as output. Demo: http://jsfiddle.net/ambiguous/tUAyZ/
Your template should say this:
{{#if NumLikes}}
<img src="images/myCommunity/like@2x.png" width="20" height="19" id="like-btn" name = "like-Button" >
{{else}}
<img src="images/myCommunity/liked@2x.png" width="20" height="19" id="like-btn" name = "like-Button" >
{{/if}}
回答2:
You would need to write an helper as below, because comparing with a value is not directly supported by handlebars.
Handlebars.registerHelper('ifCond', function(v1,options) {
if(v1 == 0) {
return options.fn(this);
}
return options.inverse(this);
});
And in your handlebar templates you need to use it as below
<div class="post-left-panel">
<div class="post-image-container">
<img src="{{UserImageURL}}" alt="" class="post-image" /></br>
{{#ifCond NumLikes}}
<img src="images/myCommunity/like@2x.png" width="20" height="19" id="like-btn" name = "like-Button" >
{{else}}
<img src="images/myCommunity/liked@2x.png" width="20" height="19" id="like-btn" name = "like-Button" >
{{/if}}
({{NumLikes}})
</div>
</div>
来源:https://stackoverflow.com/questions/22242694/how-can-i-use-if-then-else-in-hbs-backbone-template-file-i-m-using-handelsbar-f