Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your model is kind of iffy... Consider</p> <p><code>{name:"Category name", parent:"_id of parent category"}</code></p> <p>Okay, that's a lot simpler. To create a category.</p> <pre><code>var moviesId = Categories.insert({name:"Movies"}); Categories.insert({name:"Horror",parent:moviesId}); </code></pre> <p>That was easy enough. Now, to render in a way that <code>{{#each}}</code> works:</p> <pre><code>Template.categories.categories = function(parent) { if (parent) { return Categories.find({parent:parent}).fetch(); } else { return Categories.find({parent:{$exists:false}}); } } </code></pre> <p>You might be seeing where this is going...</p> <pre><code>&lt;template name="categories"&gt; {{#each categories}} &lt;ul&gt;{{name}} {{#each categories _id}} &lt;li&gt;{{name}}&lt;/li&gt; {{/each}} &lt;/ul&gt; {{/each}} &lt;/template&gt; </code></pre> <p>Now I'm not sure if the <code>{{#each}}</code> block helper can take a function argument when it calls another helper. If it doesn't...</p> <pre><code>Template.categories.categories = function() { return Categories.find({parent:{$exists:false}}).map(function(parentCategory) { return _.extend(parentCategory, {children:Categories.find({parent:parentCategory._id}).fetch()}); }); } </code></pre> <p>That's a real doozy. It returns parent categories with a new "children" list property, that contains all the children categories. Now you can do:</p> <pre><code>&lt;template name="categories"&gt; {{#each categories}} &lt;ul&gt;{{name}} {{#each children}} &lt;li&gt;{{name}}&lt;/li&gt; {{/each}} &lt;/ul&gt; {{/each}} &lt;/template&gt; </code></pre> <p>Clever, eh?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload