使用铁路由器设置查询变量

Using Iron Router to set a query variable

本文关键字:查询 变量 设置 路由器      更新时间:2023-09-26

我正在尝试使用铁路由器调用页面并按路由过滤结果。实际上,该应用程序允许您创建项目。项目包括一个数组,该数组可以有 0 到多个标记:

Item: {
  _id: <assigned by application>,
  itemTags: []
}

导航栏上的下拉列表从项目中收集所有标记,执行一些清理,然后将它们放入下拉菜单中:

// HTML
<template name="header">
  <nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
      <div class="navbar-header">
        <ul class="nav navbar-nav">
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Select List to View <span class="caret"></span></a>
            <ul class="dropdown-menu" role="menu">
              <li><a href="/list/all-list-items">All List Items</a></li>
              <li class="divider"></li>
              {{#each uniqueTags}}
              <li><a href="/list/{{this}}">{{this}}</a></li>
              {{/each}}
            </ul>
          </li>
        </ul>
      </div>
    </div>
  </nav>
</template>
// JS
Template.header.helpers({
  uniqueTags: function() {
    var allItems = Items.find({checked: false});
    var uniqueTags = allItems.map((function(allItems) {return allItems.itemTags;}));
    uniqueTags = _.flatten(uniqueTags);
    uniqueTags = _.compact(uniqueTags);
    uniqueTags = _.uniq(uniqueTags);
    uniqueTags = _.sortBy(uniqueTags, function (name) {return name;});
    return uniqueTags;
  }
});

然后路由器将您发送到"/list/"。到目前为止,一切都很好。但随后它分崩离析。我的问题是双重的:

1) 如何适当地获取数组中某处列出了标签的项目的数据上下文?

2) 如何在"列表"页面上显示这些项目?我不知道列表中应该包含什么.js以处理返回的数据上下文

我当前的代码在下面,但它被黑客入侵并且显然无法正常工作:)

// JS - router.js
Router.route('/list/:tagName', {
  name: 'list',
  data: function() { 
    return Items.find({$and: [
      {checked: false}, {listItem: true}, {itemTags: {$in: ['this.params.tagName']}}
    ]});
  }
});
// HTML - list.html
<template name="list">
  <h3><span class="label label-default view-list">List</span></h3>
  {{#each listItems}}
    {{> item}}
  {{/each}}
</template>
// JS - list.js
Template.list.helpers({
  listItems: function() {
    <somehow use the returned data context>
  }
});

感谢您的帮助!

这将起作用

  Router.route('/list/:tagName', {
    name: 'list',
    data: function() { 
    return { 'listItems' : Items.find({$and: [
          {checked: false}, {listItem: true}, {itemTags: {$in: [this.params.tagName]}}
     ]}) };
   }
  });

// HTML - list.html
<template name="list">
  <h3><span class="label label-default view-list">List</span></h3>
 {{#each listItems}}
   {{> item}}
 {{/each}}
</template>
 // You have to write a item template 
// JS - list.js
Template.list.helpers({
  //listItems: function() {
  // this helper is not required
  // you could access the data by this.data.listItems
  //<somehow use the returned data context>
  //}
});