【发布时间】:2014-09-03 16:38:41
【问题描述】:
我有两个具有一对多关系的流星集合:建筑物和空间
在我的建筑页面上,我想显示与建筑相关的空间。
目前,我是这样做的:
buildingsRoute.coffee
BuildingController = RouteController.extend(template: "buildings")
Router.map ->
@route "building",
path: "/buildings/:_id"
waitOn: ->
subs.subscribe "allBuildings"
subs.subscribe "allSpaces"
data: ->
building: Buildings.findOne(@params._id)
spaces: Spaces.find({building_id: @params._id})
建筑.翡翠:
template(name="building")
+with building
.building
.page-header.position-relative
h1.inline #{name}
.row
.col-xs-12
+spacesList
template(name="spacesList")
.widgets
.row
h1 Spaces
+each spaces
.col-xs-12.col-sm-6
.widget-box.widget-color-purple
.widget-header
a(href="{{pathFor 'space'}}") #{name}
.widget-body
p Content here
这不起作用,我猜是因为spacesList模板的数据上下文与iron router定义的用于构建的数据上下文不同。
我可以将“+each 空格”替换为“+each ../spaces”,但这对我来说似乎不是一个非常通用的解决方案(如果我想在另一个上下文中使用我的空格列表模板怎么办?)
所以我尝试在模板助手中定义数据上下文,如下所示:
Template.spacesList.helpers
spaces: Spaces.find({building_id: @params._id})
但我收到错误消息:
Spaces is not defined.
所以我有点困惑。什么是正确实现嵌套路由的流星方式?
谢谢!
编辑:
空间集合的定义:/models/space.coffee
@Spaces = new Meteor.Collection("spaces",
schema:
building_id:
type: String
label: "building_id"
max: 50
name:
type: String
label: "Name"
optional: true
max: 50
creation_date:
type: Date
label: "Creation date"
defaultValue: new Date()
)
出版物:/server/publications.coffee
# Buildings
Meteor.publish "allBuildings", ->
Buildings.find()
Meteor.publish "todayBuildings", ->
Buildings.find creation_date:
$gte: moment().startOf("day").toDate()
$lt: moment().add("days", 1).toDate()
# Publish a single item
Meteor.publish "singleBuilding", (id) ->
Buildings.find id
# Spaces
# Publish all items
Meteor.publish "allSpaces", ->
Spaces.find()
编辑 2
经过一番研究,我终于想出了一个解决方案:
Template.spacesList.helpers
spaces: () ->
if Router._currentController.params._id
subs.subscribe "buildingSpaces", Router._currentController.params._id
Spaces.find()
else
subs.subscribe "allBuildings"
Spaces.find()
nbr_spaces: () ->
Spaces.find().count()
附加出版物:
# Publish all items for building
Meteor.publish "buildingSpaces", (building_id) ->
Spaces.find({building_id: building_id})
错误是:
- 空间定义未包装到函数中的事实
- @params._id 被我用不太性感的 Router._currentController.params._id 替换,但我找不到任何快捷方式。
我仍然不知道这是否是管理嵌套路由的 Meteor(最佳)方式...
有更好的推荐吗?
【问题讨论】:
-
请包含
Spaces集合的定义和文件路径(例如/lib/collections/spaces.coffee)。另请注意,jade 中的+用于嵌套模板和自定义组件。您应该将它们从each、with等中删除。我真的很惊讶,甚至编译。 -
我将它们添加到我的帖子末尾。关于每个,如果等,它们实际上是组件。它们应该与 + 一起使用,即使它是可选的 (github.com/mquandalle/meteor-jade)。这就是它编译的原因。
-
啊,是的,您对
+s 的看法完全正确,我想我只是跳过了文档的那一部分。
标签: meteor nested iron-router