【问题标题】:How to refactor Handlebars template and helper code in Meteor when pass parameters?传递参数时如何在 Meteor 中重构 Handlebars 模板和帮助代码?
【发布时间】:2014-01-20 07:50:14
【问题描述】:

知道如何让我的 BioPic Handlebars 助手(我正在使用 Meteor)为参数“所有者”提供不同的上下文。我将 showBioPic 称为来自另一个模板的部分,即

<template name="myMain">
    {{#each post}}
        {{> showBioPic}}
    {{/each}}
    Do a bunch of other stuff here too.
</template>

我希望能够根据调用模板传递不同的“所有者”值,即 Meteor.userId、post.owner、anotherUsersId。即如果我使用 {{#each user}} 这没有所有者字段,它有一个 userId,所以 BioPic 助手将不起作用。

<template name="showBioPic">        
    {{#with BioPic owner}}
        <img src="{{cfsFileUrl 'size48x48gm'}}" alt="Profile Picture: {{_id}}">
    {{else}}
        <img class="showShared" src="images/default-biopic-48x48.png" alt="Default Profile Picture">
    {{/with}}
</template>


Template.showBioPic.BioPic = function (IN_ownerId)    
   return BioPicsFS.findOne( { owner: IN_ownerId });
};

【问题讨论】:

    标签: javascript meteor handlebars.js


    【解决方案1】:

    如果使用模板助手是一个选项,那么这样的事情应该可以工作:

    Template.myMain.helpers({
      showBioPicWithContext: function (owner) {
        return Template.showBioPic(owner);
      }
    });
    
    <template name="myMain">
        {{#each post}}
            {{showBioPicWithContext id}}
        {{/each}}
        Do a bunch of other stuff here too.
    </template>
    
    <template name="showBioPic">
        {{#if _id}}
            <img src="{{cfsFileUrl 'size48x48gm'}}" alt="Profile Picture: {{_id}}">
        {{else}}
            <img class="showShared" src="images/default-biopic-48x48.png" alt="Default Profile Picture">
        {{/if}}
    </template>
    

    【讨论】:

    • 很确定这不会起作用,因为 {{cfsFileUrl}} 需要 #each 或 #with 才能工作,它是 CollectionFS 的助手。此外,如果我需要的 _id 位于名为 owner 的字段中,则您的代码将无法按照 {{#if _id}} 需要为 {{#with owner}} 工作,这将打破我确实需要检查的情况对于 _id,如 {{#with _id}}。
    • cfsFileUrl 不是 owner 中的字段(js 中传给模板的数据对象)吗?
    • 不,cfsFileUrl 是来自 CollectionFS 的 Handlebars 助手,请参见此处:github.com/CollectionFS/Meteor-CollectionFS
    【解决方案2】:

    我不确定我是否了解您的问题的详细信息,但在我的一个项目中,我做了这样的事情:

    Handlebars.registerHelper('BioPic', function(user) {
      if (_.isString(user)) {
        // assume user is an id
      } else {
        // assume user is an object like Meteor.user()
      }
    });
    

    Handlebars 助手只是函数,因此您可以测试传递给它们的参数的值并采取相应的行动。在上面的例子中,当user 是一个字符串时,我们可以假设它是一个id 并返回类似Pictures.findOne({owner: user}); 的东西。您可以根据user 输入的所有可能变化添加更多子句。

    【讨论】:

    • 谢谢,虽然它有点像Pearl,因为函数的行为取决于传入的参数。我想避免这种歧义。如果我想不出别的办法,我仍然可以试试这个。
    • 我将所有助手保存在一个文件中,并且 is-id-or-object 测试是它们之间的常用习语,因此看起来不错。我同意如果这有两个以上的条款,那将很难维护。如果您有更好的想法,请告诉我。
    猜你喜欢
    • 2015-09-02
    • 1970-01-01
    • 2015-07-10
    • 2015-12-20
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 2016-08-24
    • 2015-08-25
    相关资源
    最近更新 更多