简体   繁体   English

流星:在特定上下文中渲染模板

[英]meteor: render a template in a specific context

I have two templates 我有两个模板

<body>
    {{>tmpl1}}
    {{>tmpl2}}
    ....
</body>

in the tmpl1 I have a list of items, which can be clicked. 在tmpl1中,我有一个项目列表,可以单击。 When one is click, tmpl2 shown the details. 单击一个时,tmpl2显示详细信息。 How can this be achieved ? 如何实现呢?

So, just to make the idea clearer, here is how I get the list of items 因此,为了使您的想法更清晰,这是我获取项目清单的方式

Template.tmpl1.items = function () {
    return Items.find({}).fetch();
};

tmpl1 displays them as follows tmpl1它们显示如下

<template name="tmpl1">
    {{#each items}}
        {{title}}
    {{/each}}
    ....
</template>

So tmpl2 template might look like this 所以tmpl2模板可能看起来像这样

<template name="tmpl1">
    <h1>{{title}}</h1>
    <p>{{content}}</p>
</template>

Any suggestions how to link the selected item in tmpl1 with tmpl2 ? 任何建议如何将tmpl1的所选项目与tmpl2

First, put your templates in a container so that you can manipulate the context. 首先,将模板放在容器中,以便您可以操纵上下文。 Also, put the details template in a #with context: 另外,将详细信息模板放在#with上下文中:

<template name="box">
  {{> list}}
  {{#with item}}
    {{> details}}
  {{/with}}
</template>

Now, add the event handlers for the box template. 现在,为box模板添加事件处理程序。 Assuming your entries in the list looks like this: 假设您在list的输入如下所示:

<div class="listItem" data-id="{{_id}}">{{title}}</div>

Write the handler: 编写处理程序:

Template.box.events({
  'click .listItem': function(e, t) {
    t.data.itemId = $(e.target).data('id');
    t.data.itemDep.changed();
  }
});

Finally, create the data helper and dependency for the selected item: 最后,为所选项目创建数据助手和依赖项:

Template.box.created = function() {
  this.data.itemDep = new Deps.Dependency();
};

Template.box.item = function() {
  this.itemDep.depend();
  return Items.findOne(this.itemId);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM