【问题标题】:Template helper inside template instantiation模板实例化中的模板助手
【发布时间】:2015-10-23 06:58:48
【问题描述】:

是否可以在模板实例化中调用模板助手?

对于我的项目,我为所有自定义样式的输入元素创建了模板,以使它们可重复使用。例如,复选框看起来像:

<template name="myCheckbox">
   <input type="checkbox" id="{{id}}" class="myCheckbox ..." />
</template>

要使用它,我只需:

{{> myCheckbox id="allowEdit"}}

这使我可以轻松控制整个项目中输入的外观和感觉,因为我只需更改模板即可更新所有复选框。这很好用,但现在我需要一个模板助手来根据数据库向我的复选框添加一个“已选中”属性。例如

Template.myTemplate.helpers({
    checkAllowEdit: function() {
        return (this.allowEdit) ? "checked" : "";
    }
});

{{> myCheckbox id="allowEdit" {{checkAllowEdit}} }}

这不起作用。 Meteor 不喜欢我尝试在实例化中使用助手。所以我的问题是: 有没有办法在模板实例化中调用模板助手?

【问题讨论】:

    标签: html meteor meteor-helper


    【解决方案1】:

    要检查助手的复选框,您可以使用this Blaze feature:让助手返回一个布尔值并将其分配给子模板的复选框checked 属性。

    Template.myTemplate.helpers({
        checkAllowEdit: function() {
            return Boolean(this.allowEdit); // Boolean cast may be unnecessary
        }
    });
    
    <template name="myTemplate">
      {{!-- things... --}}
      {{> myCheckbox id="allowEdit" checked=checkAllowEdit }}
    </template
    
    <template name="myCheckbox">
      <input type="checkbox" id="{{id}}" class="myCheckbox ..." checked={{checked}} />
    </template>
    

    更自然的方法是在 myCheckbox 模板中使用帮助器,而不是 myTemplate 一个:

    <template name="myTemplate">
      {{!-- things... --}}
      {{> myCheckbox id="allowEdit" }}
    </template>
    
    Template.myCheckbox.helpers({
        checkAllowEdit: function() {
            return Boolean(this.allowEdit); // Boolean cast may be unnecessary
        }
    });
    
    <template name="myCheckbox">
      <input type="checkbox" id="{{id}}" class="myCheckbox ..." checked={{checkAllowEdit}} />
    </template>
    

    但我感觉你是故意在myTemplate 中想要它的。

    【讨论】:

    • 正是我想要的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 2017-08-30
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多