【问题标题】:Meteor: Re-use template with different dataMeteor:重用具有不同数据的模板
【发布时间】:2013-03-08 05:48:36
【问题描述】:

我有一些模板列出项目(日志行、用户)并在表格中相应地设置它们的样式。现在我添加了一个“搜索”页面,它搜索不同项目类型的字符串并将它们显示在一个页面上。在布局方面,我想重用原来的模板,但显然是用搜索返回的数据。

如何在不将模板本身复制到 HTML 文件中的情况下做到这一点?

换句话说:如何在子模板中使用来自顶级模板的实际数据。

小例子:

<template name="user_list">
{{#each user_list}}
</template>

<template name="users">
{{> user_list}}
</template>

<template name="search">
{{> user_list}}
{{> group_list}}
</template>

在 .coffee 中:

 Template.users.user_list = ->
     [a,b,c,d]

 Template.search.user_list = ->
     [b,c]

也许这很简单,这表明我对 Meteor 了解甚少。

【问题讨论】:

    标签: javascript coffeescript meteor handlebars.js


    【解决方案1】:

    只需将您要使用的模板放在{{#each}} 语句中即可。然后数组中的每一项都将是该内部模板的上下文。

    HTML 文件

    <template name="users">
        <ul>
        {{#each UserArr}}
            {{> userItem}}
        {{/each}}
        </ul>
    </template>
    
    <template name="userItem">
        <li><a href="/edituser/{{_id}}">{{username}}</a> {{profile.name}}</li>
    </template>
    

    JS 文件

    Template.users.UserArr = function()
    {
        return Meteor.users.find({});
    };
    

    【讨论】:

      【解决方案2】:

      另一种解决方案是将您的请求放入 Session 属性中,并在查询用户时检查其是否存在。默认情况下,Session.get("userQuery") 将返回 undefined,但是一旦您在搜索字段中输入内容,您就可以使用 Session.set("userQuery", {type: "something"}) 更改它

      现在在咖啡脚本中你可以说:

      Template.users.user_list = ->
         if(Session.get("userQuery"))
           [a,b,c,d]
         else
           [b,c]
      

      或者使用 MiniMongo 查询,因为它更好:-)

      好消息是您的 HTML 将重新呈现,因为它是对 Session 内容的反应。

      【讨论】:

        猜你喜欢
        • 2017-08-09
        • 1970-01-01
        • 2015-10-27
        • 2020-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-28
        相关资源
        最近更新 更多