簡體   English   中英

傳遞參數時如何在Meteor中重構Handlebars模板和輔助代碼?

[英]How to refactor Handlebars template and helper code in Meteor when pass parameters?

任何想法如何允許我的BioPic把手助手(我正在使用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 });
};

如果可以選擇使用模板助手,那么應該可以使用以下方法:

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>

我不確定我是否了解您的問題的詳細信息,但是在我的一個項目中,我這樣做:

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

車把助手只是函數,因此您可以測試傳遞給它們的參數的值並采取相應的措施。 在上面的示例中,當user是一個字符串時,我們可以假定它是一個id並返回類似Pictures.findOne({owner: user}); 您可以僅基於user輸入的所有可能變體添加更多子句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM