使用HAML有条件地设置HTML元素ID

Sco*_*erC 18 haml if-statement ruby-on-rails

我试图用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>
Run Code Online (Sandbox Code Playgroud)

因为我不想编写辅助方法,所以我将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
Run Code Online (Sandbox Code Playgroud)

但是,'current_item'的这个​​id标签包含所有项目而不仅仅是当前项目.这导致javascript突出显示所有或错误的条目.关于如何让haml合作的想法?

Rad*_*sky 33

恩先生,你的病情错了:-)

它应该是

line_item == @current_item ? "current_item" : ""
Run Code Online (Sandbox Code Playgroud)

有一件事情并不漂亮 - 你最终会id=""得到其余的东西.但有一个简单的治疗方法:

%tr.lineitem{ :id => (line_item == @current_item ? "current_item" : nil)}
Run Code Online (Sandbox Code Playgroud)

当您返回nil属性的值时,HAML将忽略它,它将不会出现在输出中.


vla*_*iov 5

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

= f.input_field :hello, disabled: (true unless SOME_CONDITION_HERE)
Run Code Online (Sandbox Code Playgroud)