【问题标题】:JsRender if condition fails inside custom range tags如果条件在自定义范围标记内失败,则 JsRender
【发布时间】:2014-02-18 21:36:27
【问题描述】:

我正在尝试将选定的类添加到范围标记内的 img 标记中。

 <ul class="cci-TweetContainer">
  {{range refTweets start=0 end=9}}
    <li data-userID="{{:userId}}">
      <a href="javascript:void(0);" alt="User Avatar" data-userID="{{:userId}}">
          {{if refTweets == 0}}
            <img class="selected" src="{{:userAvatar}}" alt="User avatar icon" width="25" height="25" />
          {{else}}
            <img src="{{:userAvatar}}" alt="User avatar icon" width="25" height="25" />
          {{/if}}
      </a>
    </li>
   {{/range}} 
  </ul>

【问题讨论】:

    标签: if-statement jsrender


    【解决方案1】:

    refTweets 是一个数组吗?如果是这样,那么在 {{range}} 内,当前数据对象将是 refTweets 数组中的当前项目。所以测试refTweets == 0 似乎没有意义。您实际上正在测试当前对象上的 refTweets 属性 - 所以refTweet.refTweets == 0 - 这将始终是错误的。

    你可以像这样传递上下文:

    {{range refTweets ~selId=selectedId start=0 end=9}} <li data-userID="{{:userId}}"> <a href="javascript:void(0);" alt="User Avatar" data-userID="{{:userId}}"> {{if userId === ~selId}} ... {{else}} ... {{/if}} </a> </li> {{/range}}

    (假设您在具有 refTweets 属性的同一对象上具有 selectedId 属性)。

    【讨论】:

    • 谢谢 Boris,我同意您的解决方案,但通过在 if 条件下查询 #getIndex(#parent) == 0 得到了一个更简单的解决方案。
    【解决方案2】:

    通过添加引用 refTweets 属性的#getIndex(#parent) 使代码正常工作。

    {{range refTweets start=0 end=9}}
            <li data-userID="{{:userId}}">
              <a href="javascript:void(0);" alt="User Avatar" data-userID="{{:userId}}">
                  {{if #getIndex(#parent) == 0}}
                    <img class="selected" src="{{:userAvatar}}" alt="User avatar icon" width="25" height="25" />
                  {{else}}  
                    <img src="{{:userAvatar}}" alt="User avatar icon" width="25" height="25" />
                  {{/if}}  
              </a>
            </li>
    {{/range}}
    

    【讨论】:

    • 实际上 getIndex() 不带参数,所以传入#parent 并没有做任何事情。这相当于写 {{if !#getIndex()}}。
    • 事实上你甚至可以只写 {{if !#index}} - 你只是选择列表中的第一项。 (从你的问题中不清楚这就是你想要的......)
    • 抱歉,下次我会尝试更具体的。不过感谢您抽出宝贵时间回答我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    相关资源
    最近更新 更多