Meteor / Blaze rendering : {{each}} in another {{each}} doesn't return the right data (data context)

◇◆丶佛笑我妖孽 提交于 2019-12-24 17:50:02

问题


I was wondering if you could give me some clue how to tackle this 'problem'. I'm a newbie in JS (+ Meteor), so it might be super simple for you. I'm working with helpers and blaze/spacebars for rendering.

I have a simple helper:

Template.monitoring.helpers({

    'realtime': function(){
        return {
            house:    house.find( {} ),
            neighbours: neighbours.find( {} ),
        }
    } // end of realtime

}); // end of helpers

At this point, everything is OK. I'm able to retrieve the data I want. The problem is that I'm not able to render it like I want. Below my template.

<template name="monitoring">

   {{#each realtime.house}}
   <div class="card red">
     SHOW STUFF ABOUT HOUSE
   </div>

    <div class="card blue">
        {{#each realtime.neighbours}}
        SHOW STUFF ABOUT NEIGHBOURS OF THE SPECIFIC HOUSE
        {{/each}}
  </div>

  {{/each}} -> end of each realtime.house

</template>

More precisely, when my template is rendered:

  • number of red cards = number of houses => perfect
  • each red card contains the data of one house => perfect

  • number of blue cards = number of houses => perfect

  • each blue card contains the data of all neighbours => WRONG. What I want is the data of neighbours concerning the specific house

Do you have how to get the right stuff at the right place? Thank you very much.


回答1:


You need two helpers: one which returns the houses, and one which returns the neighbors with a house as its context. Without the schema, I can't give a precise answer but let's assume each neighbor has a houseId property which joins the two.

Template.monitoring.helpers({
  houses: function () {
    return house.find();
  },

  neighbors: function () {
    // Note the context here is a house because it's
    // called from within an each.
    return neighbours.find({ houseId: this._id });
  },
});

And your template would look something like this (assuming neighbors should each be in a blue card):

<template name="monitoring">
  {{#each houses}}
    <div class="card red">
      SHOW STUFF ABOUT HOUSE
    </div>
    {{#each neighbours}}
      <div class="card blue">
        SHOW STUFF ABOUT NEIGHBOURS OF THE SPECIFIC HOUSE
      </div>
    {{/each}}
  {{/each}}
</template>


来源:https://stackoverflow.com/questions/37509905/meteor-blaze-rendering-each-in-another-each-doesnt-return-the-right

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