In templates in Ember.js, how do you refer to a value in the parent context when you are inside an #each block?

前端 未结 4 763
栀梦
栀梦 2020-12-25 08:58

I have a situation in a template where I want to use an if block on a value in the parent context while inside an each block.

The code:

App = Ember.A         


        
4条回答
  •  臣服心动
    2020-12-25 09:02

    What hekevintran's answer means is that you can rename any variable using #with. We have a similar problem in JavaScript with this. In JavaScript, sometimes you'll see code like this to work around it.

    var self = this;
    doSomething(function() {
      // Here, `this` has changed.
      if (self.bar) {
        console.log(this);
      }
    });
    

    In Ember flavored Handlebars, something similar is happening with view. Say you have App.MyOuterView and another view inside it. You can work around it like this.

    {{#with view as myOuterView}}
      {{#each foo}}
        {{#if myOuterView.bar}}
          {{this}}
        {{/if}}
      {{/each}}
    {{/with}}
    

    Similar to the JavaScript, you can essentially rename view to something else so it doesn't get shadowed by the inner view. {{#each person in people}} is just a special case of that. But renaming using {{#with view as myView}} is the more general solution/workaround to this problem that also works with nested calls to the view helper.

提交回复
热议问题