简体   繁体   中英

How Do I Nest Spacebars Tags?

I have a problem. I have a collection of documents in my database, and I would like to display each document depending on whether a session variable corresponding to that document is set.

To illustrate my problem, let me give a simplified example.

Meteor.myTemplate.helpers({
  stuff: [
    {name: 'item1'},
    {name: 'item2'}
    {name, 'item3'},
    {name: 'item4'},
    {name: 'item5'}
  ],
  isActive: function (itemName) {
    return Session.get(itemName + 'IsActive');
  }
});

Now, what I would like to do is this:

{{#each stuff}}
    {{#if isActive {{name}} }}
      {{> someTemplate}}
    {{/if}}
{{/each}}

But since nested tags like this are not supported, I can't do this. I am looking for a way to achieve this without having to write:

{{if isActive 'item1'}}{{> someTemplate}}{{/if}}
{{if isActive 'item2'}}{{> someTemplate}}{{/if}}
{{if isActive 'item3'}}{{> someTemplate}}{{/if}}
{{if isActive 'item4'}}{{> someTemplate}}{{/if}}
{{if isActive 'item5'}}{{> someTemplate}}{{/if}}

Which is possible if the data is static like in the above example (instead of coming from a database cursor), but it is not really practical in any case, especially with a lot of items. Furthermore, this style probably makes every programmer cringe.

Since the context of isActive is a stuff , then this.name should be available to the helper:

Template.myTemplate.helpers({
  isActive: function(itemName) {
    return Session.get(this.name + 'IsActive');
  }
});

Your template would look like:

{{#each stuff}}
  {{#if isActive}}
    {{> someTemplate}}
  {{/if}}
{{/each}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM