【问题标题】:Conditionally set HTML element id with HAML使用 HAML 有条件地设置 HTML 元素 id
【发布时间】:2011-04-19 23:01:39
【问题描述】:

我正在尝试用 haml 编写这个 html,以便在项目是当前项目时添加一个 id 标记。这是为 jquery 高亮设置的。

<% if line_item == @current_item %>
<tr class="line_item id="current_item">
<% else %>
<tr class="line_item">
<% end %> 
  <td><%= line_item.quantity %>&times;</td>
  <td><%= line_item.product.title %></td> 
  <td class="item_price"><%= number_to_currency(line_item.total_price) %></td>
</tr>

因为不想写辅助方法,所以把if语句卡在了标签里面:

%tr.line_item{ :id => (line_item == @current_item ? '' : 'current_item') }
%td
    = line_item.quantity
%td 
    \x #{line_item.product.title}
%td.item_price
    = number_to_currency(line_item.total_price)
%td.item_remove
    = button_to 'Remove', line_item, :method => :delete

但是,'current_item' 的这个 id 标记会与所有项目保持一致,而不仅仅是当前项目。这会导致 javascript 突出显示所有或错误的条目。关于如何让haml合作的想法?

【问题讨论】:

    标签: ruby-on-rails if-statement haml


    【解决方案1】:

    嗯,先生,您的情况不对:-)

    应该是

    line_item == @current_item ? "current_item" : ""
    

    有一点不太好——你最终得到了id="" 来处理其余的项目。但有一个简单的治疗方法:

    %tr.lineitem{ :id => (line_item == @current_item ? "current_item" : nil)}
    

    当您为属性返回 nil 值时,HAML 将忽略它并且不会出现在输出中。

    【讨论】:

    • 谢谢!希望我能让它更干净
    • 这就是让我心疼的“”! :-)
    • 在 HAML 中使用 nil 来“忽略”一个属性的能力是一个很好的技巧 - 感谢您指出这一点!
    • 你可以这样做:@tr.lineitem{class: ("current_item" if line_item == @current_item)}
    • 为什么你必须在这里显式返回 nil 并返回一个三元组,而不是仅仅执行 ("current_item" if line_item == @current_item)?我认为if 会在不满足条件时默认返回 nil。
    【解决方案2】:

    这也可以作为已接受答案中第一个解决方案的替代方法

    = f.input_field :hello, disabled: (true unless SOME_CONDITION_HERE)
    

    【讨论】:

    • 这对于布尔属性(如禁用)特别有用。
    【解决方案3】:

    在问题的上下文中接受@vladCovaliov 的回答:

    %tr.line_item{ id: (@current_item unless @current_item != line_item) }
    

    【讨论】:

      猜你喜欢
      • 2019-08-19
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      相关资源
      最近更新 更多