Accessing parent context in Meteor templates and template helpers

前端 未结 9 652
别跟我提以往
别跟我提以往 2020-12-09 01:10

I\'m running into a template context situation that I\'m having a hard time finding a way around.


Here\'s the template in question:



        
相关标签:
9条回答
  • 2020-12-09 01:34

    Simply register a global template helper:

    Template.registerHelper('parentData',
        function () {
            return Template.parentData(1);
        }
    );
    

    and use it in your HTML templates as:

    {{#each someRecords}}
      {{parentData.someValue}}
    {{/each}}
    

    ======= EDIT

    For Meteor 1.2+, you shold use:

    UI.registerHelper('parentData', function() {
      return Template.parentData(1);
    });
    
    0 讨论(0)
  • 2020-12-09 01:46

    I was stuck in a similar way and found that the Template.parentData() approach suggested in other answers currently doesn't work within event handlers (see https://github.com/meteor/meteor/issues/5491). User Lirbank posted this simple workaround:

    Pass the data from the outer context to an html element in the inner context, in the same template:

    {{#each companies}}
      {{#each employees}}
        <a href="" companyId="{{../id}}">Do something</a>
      {{/each}}
    {{/each}}
    

    Now the company ID can be accessed from the event handler with something like

    $(event.currentTarget).attr('companyId')
    
    0 讨论(0)
  • 2020-12-09 01:52

    I don't know the formal way (if there is one), but to solve your issue, I would link the participants with the parent ID like this:

    {
        _id: "1234",
        question: "Whats up?",
        ...
        participants: [
          {
            _id: "abcd",
            parent_id: "1234",
            vote: 0
          }
        ]
    }
    

    and use this parent_id in helpers, events, etc. to jump back to the parent using findOne. That is obviously a sub optimal thing to do, but it's the easiest way that comes to my mind as long as there is no way of referencing the parent context. Maybe there is a way but it is very well hidden in the inner workings of Meteor without mention in the docs, if so: Please update this question if you find one.

    0 讨论(0)
提交回复
热议问题