Meteor:获取要在子模板上使用的数据

时间:2016-03-20 13:25:40

标签: javascript mongodb meteor

这就是我尝试将文章显示为用户和编辑器视图的方式。我不使用任何路由器,所以我在onCreated进行订阅。

但是我不喜欢它为标题和内容做一个findOne()。我想我可以在一个查找请求中获取完整数据,并在两个模板(用户/编辑器)中使用此数据。但是我该怎么做呢?

模板

<template name="example">
    {{#if isEditorView}}
        {{ > editor }}
    {{else}}
        {{ > user }}
    {{/if}}
</template>

<template name="editor">
    <input type="text" placeholder="title" value="{{title}}">
    <textarea placeholder="article">{{content}}</textarea>
</template>

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

助手

Template.example.onCreated(function() {
    Meteor.subscribe('articles');
});

Template.example.helpers({
    isEditorView: function() { 
        return Session.get('editorView') ? true : false; 
    },

    title: function() {
        var doc = Collection.findOne();
        return doc.title;
    },

    content: function(plain) {
        var doc = Collection.findOne();
        return doc.content; 
    }
});

1 个答案:

答案 0 :(得分:2)

使用{{#with }}设置数据上下文:

<template name="example">
{{#with doc}}
  {{#if isEditorView}}
    {{ > editor }}
  {{else}}
    {{ > user }}
  {{/if}}
{{/with}}
</template>

然后你只需要一个帮手:

Template.example.helpers({
  isEditorView: function() { 
    return Session.get('editorView') ? true : false; 
  },
  doc: function() {
    return Collection.findOne();
  }
});