在Spacebars中检查是否相等? [英] Check for equality in Spacebars?

查看:128
本文介绍了在Spacebars中检查是否相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做我认为应该是一项非常简单的任务,但过去一小时内没有这样做。如果用户属性与值匹配,我想默认选择一个选项。

I am trying to do what I think should be a very simple task, but have been failing to do so in the past hour. I want to select a select option by default if the user property matches the value.

<select name="myName">
  {{#each addKeys myTable}} <!-- addKeys creates variables for keys and values -->
    <option value="{{key}}" {{#if currentUser.property === key}}selected="selected"{{/if}}>{{value}}</option>
  {{/each}}
</select>

现在我认为这很简单,可以实施。但事实证明,Spacebars不允许除否定感叹号之外的条件运算符,因此等号无关紧要。然后我尝试了一些可怕的尝试:

Now I thought this was straightforward enough to be implemented. But it turns out that Spacebars do not allow conditional operators other than the negation exclamation mark, so equal signs are out of question. I then tried something horrible for the sake of trying:

在模板 myTemplate

<select name="myName">
  {{#each addKeys myTable}}
    <option value="{{key}}" {{isSelected currentUser.property key}}>{{value}}</option>
  {{/each}}
</select>

mytemplate.js

Template.myTemplate.helpers({
  isSelected: function(v1, v2) {
    if (v1 === v2)
      return "selected=\"selected\"";
    return '';
  }
});

此代码不仅可怕,看起来很糟糕,不起作用:

Not only is this code terrible, terrible to look at, it does not work:

Exception in Meteor UI: String contains an invalid character

我不明白为什么这么简单的东西似乎无法实现。我错过了什么?

I don't understand why something that simple seems so impossible to achieve. Am I missing something there?

推荐答案

试试这个:

In您的模板:

< option value = {{key}} selected = {{isSelected currentUser.property key}}>

然后让你的助手返回一个布尔值。

Then have your helper return a boolean.

有关此主题的更多信息: https://github.com/meteor/meteor/ wiki / Using-Blaze#conditional-attributes-with-no-value-eg-checked-selected

More on the topic here: https://github.com/meteor/meteor/wiki/Using-Blaze#conditional-attributes-with-no-value-eg-checked-selected

这篇关于在Spacebars中检查是否相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆