Turn a meteor method returning a single object into a context for handlebar

馋奶兔 提交于 2019-12-22 09:40:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!