Meteor recursive template doesn't work

2019-08-09 14:52发布

I tried to have a recursive template like this:

<template name="generate">
  {{#if elements}}
    {{#each elements}}
      <div>{{#if elements}}{{> generate}}{{/if}}</div>
    {{/each}}
  {{else}}
    {{> generate elements=getElements}}
  {{/if}}
</template>

with the helper:

Template.generate.helpers({
  getElements: function() {
    return Elements.find()
  }
})

and the "Elements" data object:

[{ 
  _id : "fgQ4GHrrZGFFGWPZQ", 
  elements" : [{
    _id : "hY8iAYJC4KBwGKN84",  
    elements : [] 
  }]
},{ 
  _id : "rtMNfaQYwqzNTYqoD", 
  elements : [{
    _id : "p2wJeGdtiGMYBQtpW",  
    elements : [] 
  }]
}]

I'm running into an issue where the keyboard events become unresponsive and other functionality ceases to work. Were templates not designed to handle this kind of recursion? If so, I'll try a different approach but I figured this would work though. Anyone else seeing this or have any suggestions? Thanks!

Edit: This will work. My problem was setting up a keyboard event handler on the "rendered" callback which was being called more than once (each time the template was rendered) which caused the issue I mentioned. I would delete this question but stackoverflow. Thanks everybuddy!

2条回答
时光不老,我们不散
2楼-- · 2019-08-09 15:07

Unlike Javascript, Spacebars considers an empty array [] to be falsy. So the initial {{#if elements}} on leaf nodes (which have elements: []) will be false, triggering the {{> generate elements=getElements}} which ultimately causes an infinite recursion.

You could fix this by removing the {{#if}} altogether, and then calling {{> generate elements=getElements}} when you initially include generate:

<body>
    {{> generate elements=getElements}}
</body>

<template name="generate">
    {{#each elements}}
        <div>{{#if elements}}{{> generate}}{{/if}}</div>
    {{/each}}
</template>
查看更多
甜甜的少女心
3楼-- · 2019-08-09 15:27

You have some errors here.

First. you have a helper named getElements and you are calling it like elements

Second you are calling the template into the same template {{> generate}}

<template name="generate">
  {{#if elements}}
    {{#each  getElements}}
      <div>{{#if elements}}{{> anotherTemplateName}}{{/if}}</div>
    {{/each}}
  {{else}}
    {{> generate elements=getElements}}
  {{/if}}
</template>

Also how the elements helper looks? {{#if elements}}

A suggestion will be using nested templates here.

<template name="generate">
      {{#if elements}}
        {{> generateExample}}
      {{else}}
        {{> generate elements=getElements}}
      {{/if}}
    </template>

<!-- Generate Example Template -->

    <template name="generateExample">
            {{#each  getElements}}
              <div>{{#if elements}}{{> anotherTemplateName}}{{/if}}</div>
            {{/each}}
    </template>

Take a look into this Understanding Spacebars for a better learning experience

查看更多
登录 后发表回答