【问题标题】:HAML Ruby - conditionalsHAML Ruby - 条件
【发布时间】:2012-05-06 19:36:46
【问题描述】:

我正在浏览“Agile Web Dev with Rails”一书中的示例,但将它与我发现有用的额外技术混合在一起——比如 haml。 遇到一个棘手的问题,如何写下这个 erb 部分:

<% if line_item == @current_item %>
<tr id="current_item">
<% else %>
<tr>
<% 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 line_item==@current_item
 %tr#current_item
-else
 %tr
%td!=line_item.quantity.to_s+"&times;"
%td=line_item.product.title
%td.item_price=number_to_currency(line_item.total_price)

但它会打印出一个没有 TD 的空 TR...

【问题讨论】:

  • 当缩进回退一个级别时,TR标签将被关闭。
  • 没错,但我必须退回一级缩进来结束 if 语句...
  • 正确,如所写,你会;虽然 Dylan 的回答是正确的,但 IMO 这可能属于部分。

标签: ruby haml erb


【解决方案1】:

而不是有两个单独的%tr 条目(在这种情况下,我认为您需要在每个 tr 下列出您的 3 个 td),您可以只在条件中设置 id:

%tr{:id => (line_item == @current_item) ? "current_item" : false}
  %td!=line_item.quantity.to_s+"&times;"
  %td=line_item.product.title
  %td.item_price=number_to_currency(line_item.total_price)

【讨论】:

  • 如果 Haml 属性哈希中的值为 false,则该属性将被完全省略,因此您可以使用 (line_item == @current_item) ? "current_item" : false,这将更接近原始 erb。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-01
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
相关资源
最近更新 更多