Meteor 模型树结构:获取 id 的最佳方式以及如何创建嵌套 list-output
Meteor model tree structure: best way getting id and how to create nested list-output
我有一篇文章由六个部分组成。每个部分都有多个 list-items。也可以选择一些项目合并到一个组中。
因此我决定使用带有 parent 引用的模型树结构:
collection
中的文档
_id: item_1, parent: null, title: 'item 1'
_id: item_2, parent: null, title: 'item 2'
_id: item_3, parent: item_2, title: 'item 3'
_id: item_4, parent: item_2, title: 'item 4'
_id: item_5, parent: null, title: 'item 5'
我认为这是将一些元素放入另一个组的最简单方法。我也在考虑构建 _id 的最佳方式。所以我想使用文章本身的 _id,section-number 和计数:aid_2_4(=第二部分和第四个元素)。
- 这是个好方法还是您有更好的主意?也许我只需要计数?
- 对于计数,我会做以下事情:在每次插入之前,我都会用过滤器计算这个collection中的元素,所以我只是把新值作为_id。这样做有什么坏处吗?
- 我的最后一个问题是如何快速获得此输出?
输出
<li>item 1</li>
<li>item 2
<ul>
<li>item 3</li>
<li>item 4</li>
</ul>
</li>
<li>item 5</li>
由于编辑可以 change/create 组,此输出应自动更新(就像 meteor 中的其他所有内容一样)。
您需要一些 blaze 模板递归!
html:
<template name="section">
<ul>
{{#each children}}
<li>{{title}}</li>
{{#if hasChildren}}
{{>section}}
{{/if}}
{{/each}}
</ul>
</template>
js:
Template.section.helpers({
children: function(){
return Sections.find({ parent: this._id });
},
hasChildren: function(id){
return Sections.find({ parent: this._id }).count() > 0;
}
});
或类似的东西。 Here's a related q&a 这也可能有帮助。
感谢@Mathias Eckhart 将其转换为 meteorpad 并修复了数据上下文问题。
我有一篇文章由六个部分组成。每个部分都有多个 list-items。也可以选择一些项目合并到一个组中。 因此我决定使用带有 parent 引用的模型树结构:
collection
中的文档_id: item_1, parent: null, title: 'item 1'
_id: item_2, parent: null, title: 'item 2'
_id: item_3, parent: item_2, title: 'item 3'
_id: item_4, parent: item_2, title: 'item 4'
_id: item_5, parent: null, title: 'item 5'
我认为这是将一些元素放入另一个组的最简单方法。我也在考虑构建 _id 的最佳方式。所以我想使用文章本身的 _id,section-number 和计数:aid_2_4(=第二部分和第四个元素)。
- 这是个好方法还是您有更好的主意?也许我只需要计数?
- 对于计数,我会做以下事情:在每次插入之前,我都会用过滤器计算这个collection中的元素,所以我只是把新值作为_id。这样做有什么坏处吗?
- 我的最后一个问题是如何快速获得此输出?
输出
<li>item 1</li>
<li>item 2
<ul>
<li>item 3</li>
<li>item 4</li>
</ul>
</li>
<li>item 5</li>
由于编辑可以 change/create 组,此输出应自动更新(就像 meteor 中的其他所有内容一样)。
您需要一些 blaze 模板递归!
html:
<template name="section">
<ul>
{{#each children}}
<li>{{title}}</li>
{{#if hasChildren}}
{{>section}}
{{/if}}
{{/each}}
</ul>
</template>
js:
Template.section.helpers({
children: function(){
return Sections.find({ parent: this._id });
},
hasChildren: function(id){
return Sections.find({ parent: this._id }).count() > 0;
}
});
或类似的东西。 Here's a related q&a 这也可能有帮助。
感谢@Mathias Eckhart 将其转换为 meteorpad 并修复了数据上下文问题。