模板实例化中的模板助手
Template helper inside template instantiation
是否可以在模板实例化中调用模板助手?
对于我的项目,我为所有自定义样式的输入元素创建了模板,以使其可重复使用。例如,复选框看起来像:
<template name="myCheckbox">
<input type="checkbox" id="{{id}}" class="myCheckbox ..." />
</template>
要使用它,我只需:
{{> myCheckbox id="allowEdit"}}
这使我可以轻松控制整个项目中输入的外观和感觉,因为我只需要更改模板即可更新所有复选框。这工作正常,但现在我需要一个模板助手来根据数据库向我的复选框添加一个 "checked" 属性。例如
Template.myTemplate.helpers({
checkAllowEdit: function() {
return (this.allowEdit) ? "checked" : "";
}
});
{{> myCheckbox id="allowEdit" {{checkAllowEdit}} }}
这行不通。 Meteor 不喜欢我尝试在实例化中使用助手。所以我的问题是:
有没有办法在模板实例化中调用模板助手?
要检查助手的复选框,您可以使用 this Blaze feature:让您的助手 return 一个布尔值,然后将其分配给子模板的复选框 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
是故意要它的。
是否可以在模板实例化中调用模板助手?
对于我的项目,我为所有自定义样式的输入元素创建了模板,以使其可重复使用。例如,复选框看起来像:
<template name="myCheckbox">
<input type="checkbox" id="{{id}}" class="myCheckbox ..." />
</template>
要使用它,我只需:
{{> myCheckbox id="allowEdit"}}
这使我可以轻松控制整个项目中输入的外观和感觉,因为我只需要更改模板即可更新所有复选框。这工作正常,但现在我需要一个模板助手来根据数据库向我的复选框添加一个 "checked" 属性。例如
Template.myTemplate.helpers({
checkAllowEdit: function() {
return (this.allowEdit) ? "checked" : "";
}
});
{{> myCheckbox id="allowEdit" {{checkAllowEdit}} }}
这行不通。 Meteor 不喜欢我尝试在实例化中使用助手。所以我的问题是: 有没有办法在模板实例化中调用模板助手?
要检查助手的复选框,您可以使用 this Blaze feature:让您的助手 return 一个布尔值,然后将其分配给子模板的复选框 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
是故意要它的。