问题
In the basic leaderboard example on meteor.com there is a method called selected_name.
Template.leaderboard.selected_name = function () {
var player = Players.findOne(Session.get("selected_player"));
return player && player.name;
};
{{#if selected_name}}
<div class="details">
<div class="name">{{selected_name}}</div>
<input type="button" class="inc" value="Give 5 points" />
</div>
{{/if}}
Instead I would like to return the entire player object and then have that object be treated as a context by handlebar. I wish I could say this:
Template.leaderboard.selected_person = function () {
var player = Players.findOne(Session.get("selected_player"));
return player || false;
};
{{#if selected_person}}
<div class="details">
<div class="name">{{name}}</div>
<input type="button" class="inc" value="Give 5 points" />
</div>
{{/if}}
The #if block above does not actually work in meteor. The #if statement is just evaluating the selected_person method and the nested {{name}} does absolutely nothing. I would like to know if it is possible to write a method so that the returned object can be used as the context of an #if block.
回答1:
Solved! If I just use #with instead of #if then everything works great. As it says in the handlebar docs You can shift the context for a section of a template by using the built-in with block helper.
{{#if selected_person}}
{{#with selected_person}}
<div class="details">
<div class="name">{{name}}</div>
<input type="button" class="inc" value="Give 5 points" />
</div>
{{/with}}
{{/if}}
The nested if/with is quite cumbersome and clearly not worth it for only rendering the name, but I could think of times where special rendering for more attributes of a single object would be useful.
回答2:
I did a similar thing like this, but I don't think it is the "right way"?
Template.leaderboard.selected_person = function () {
return Players.find(Session.get("selected_player"));
};
{{#each selected_person}}
<div class="details">
<div class="name">{{name}}</div>
<input type="button" class="inc" value="Give 5 points" />
</div>
{{/each}}
来源:https://stackoverflow.com/questions/10160455/turn-a-meteor-method-returning-a-single-object-into-a-context-for-handlebar