【问题标题】:Setting checkbox true or false value from helper in Meteor从 Meteor 中的助手设置复选框 true 或 false 值
【发布时间】:2015-02-26 19:41:10
【问题描述】:

如何将存储的 true 或 false 值应用于选中的属性?

我有一系列问题,用户可以在其中打开/关闭(真/假)作为答案。我在 Meteor.user().profile 中创建了一个名为 questions 的对象。字段名称是问题,存储的值是truefalse

现在我希望每个字段的属性显示存储的值,而不是重置为其默认值。

<template name="template">
 {{#with currentUser.profile.questions}}
 <div class="row">
 <input  data-name="profile.questions.school" type="checkbox"  name="questions" checked="{{school}}"> Go to School?
 </div>
 <div class="row">
 <input data-name="profile.questions.contributor" type="checkbox" name="questions" checked={{contributor}}"> contributor?
 </div>
 {{/with}}
</template>

我这样做是不是很啰嗦?无论如何使用空格键{{isChecked}} 方法会有所帮助吗? https://www.discovermeteor.com/blog/spacebars-secrets-exploring-meteor-new-templating-engine/ 似乎只是为了显示复选框。

【问题讨论】:

  • 空格键中没有isChecked 这样的东西。但是,使用&lt;input type="checkbox" checked="{{value}}"&gt;,其中valuetruefalse,应该可以工作。见github.com/meteor/meteor/wiki/…

标签: html meteor spacebars


【解决方案1】:

我处理复选框/收音机的方式是这样的:

Template.myTemplate.helpers({
  isMyCheckboxChecked: function(value) {
    return (value == true ? 'checked' : '');
  }
});

然后在我的模板中我可以这样做:

<input name="myCheckbox" type="checkbox" value="true" {{isMyCheckboxChecked myCheckboxValue}} />

这假设您传入一个值以确定是否需要选中复选框。如果您的价值观几乎完全是真/假,我什至会考虑使用Template.registerHelper 使助手“全局”。代码几乎相同,您只需定义帮助程序略有不同。这将使它在所有模板中都可用。

【讨论】:

  • 我试过了,得到Uncaught Error: Expected valid attribute name, '', null, or object
  • 然后尝试返回“checked='checked'”
  • 我走了另一条路,使用了checked={{ isChecked myVar }}。无论哪种方式,您的解决方案中的代码都无法按原样运行。
  • 连同return (value == 'on' ? 'checked' : false); btw,但空的也可以。
猜你喜欢
  • 2012-01-09
  • 2014-06-17
  • 2013-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
相关资源
最近更新 更多