【问题标题】:Meteor + Blaze - If else statementMeteor + Blaze - If else 语句
【发布时间】:2015-02-14 15:32:59
【问题描述】:

查看此Using Blaze 指南,Blaze 似乎支持{{#if}}{{else}} 语句,但我还没有看到 if-else 语句的示例。 Blaze 是否支持此功能?或者我是否必须在 else 块内做一个额外的 if 块,这会变得很难看。

我试过{{else if}},但出错了。

{{#if en}}{{text.en}}{{else if tc}}{{text.tc}}{{/if}}

【问题讨论】:

    标签: meteor meteor-blaze


    【解决方案1】:

    当前版本的 Blaze 支持 else if - 请参阅下面的示例格式和对 github 问题解决方案的参考。

    {{#if isUserProfile}}
        <h3>User Profile</h3>
    {{else if isLawyerProfile}}
        <h3>Lawyer Profile</h3>
    {{else}}
        <h3>Test</h3>
    {{/if}}
    

    参考链接:GitHub Else If Issue Resoltion

    【讨论】:

      【解决方案2】:

      继 @David Wheldon 的出色回答之后,还值得注意的是,您可以从 Blaze 模板将参数传递给 JavaScript 帮助函数。

      因此,例如,下面的代码通过调用带有行 isSelected region customerCompany 的辅助方法来选择性地呈现选择列表的选项:

          {{#if isSelected region customerCompany}}
              <option value={{region._id}} selected>{{region.name}}</option>
          {{else}}
              <option value={{region._id}}>{{region.name}}</option>
          {{/if}}
      

      然后在js文件中:

      isSelected: function (region, customer) {
      
          return customer.salesRegionId === region._id;
      },
      

      通常建议使用这种将变量传递给助手的方法,以避免在使用模板时因this 关键字的含义变化而引起混淆。

      【讨论】:

        【解决方案3】:

        空格键使用与handlebars 相同的控制流结构,因此答案与this one 相同。在你的情况下:

        {{#if en}}
          {{text.en}}
        {{else}}
          {{#if tc}}
            {{text.tc}}
          {{/if}}
        {{/if}}
        

        附注 - jade 的优点之一是它支持 else if


        有时更好的选择是将逻辑移动到这样的助手中:

        Template.myTemplate.helpers({
          textValue: function() {
            if (this.en) {
              return this.text.tc;
            } else if (this.tc) {
              return this.text.tc;
            }
          }
        });
        
        <template name="myTemplate">
          <p>{{textValue}}</p>
        </template>
        

        【讨论】:

        • 感谢您的回答。但是如果我有很多很多 else if 语句怎么办?这样做会很丑陋。没有其他选择吗?
        • 单独使用模板,别无选择。我建议添加一个模板助手来返回您需要的值。
        • 我现在不知道该怎么做。我会阅读它。感谢您的回答和澄清!我已经用完了今天的所有选票。明天会 +1!
        • 我刚刚尝试过这个,我不得不将{{#else}} 更改为{{else}}
        • 谢谢@canotto90 - 我刚刚修正了这个错误。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-09
        • 2017-02-05
        • 2015-07-06
        • 2012-08-05
        • 1970-01-01
        • 2021-09-11
        相关资源
        最近更新 更多