Rails视图中的switch case

30

我想在我的视图中编写switch case:

<% @prods.each_with_index do |prod, index|%>
    <% case index %>
        <% when 0 %><%= image_tag("#{prod.img}", :id => "one") %>
        <% when 1 %><%=  image_tag("#{prod.img}", :id => "two") %>
        <% when 2 %><%= image_tag("#{prod.img}", :id => "three") %>
    <% end %>
<% end %>

但它不起作用。我是否需要在每行中添加<%end%>?有任何想法吗? 谢谢!

6个回答

63
你应该将第一个whencase放在同一块中。
<% @prods.each_with_index do |prod, index|%>
  <% case index 
     when 0 %><%= image_tag prod.img, :id => "one") %>
  <% when 1 %><%= image_tag prod.img, :id => "two") %>
  <% when 2 %><%= image_tag prod.img, :id => "three") %>
  <% end %>
<% end %>

20

不要在视图中添加太多逻辑。

我会添加一个帮助函数。

def humanize_number(number)
    humanized_numbers = {"0" => "zero", "1" => "one"}
    humanized_numbers[number.to_s]
end

你可以从视图中调用它。

<%= image_tag("#{prod.img}", :id => humanized_number(index)) %>

+1 因为提供了一个辅助方法,而不仅仅是讲课! - D_Bye

4

首先,您应该考虑将这个功能抽象成一个帮助方法,以避免在视图中添加逻辑而导致混乱。

其次,在ERB中使用case语句有点棘手,因为erb解析代码的方式不同。您可以尝试使用以下替代方法(由于当前没有可用的ruby,未经测试):

<% @prods.each_with_index do |prod, index|%>
  <% case index
    when 0 %>
      <%= image_tag("#{prod.img}", :id => "one") %>
    <% when 1 %>
      <%= image_tag("#{prod.img}", :id => "two") %>
    <% when 2 %>
      <%= image_tag("#{prod.img}", :id => "three") %>
  <% end %>
<% end %>

更多信息请参见 主题讨论。


3
你也可以使用 <%- case index -%> 语法:
<% @prods.each_with_index do |prod, index| %>
  <%- case index -%>
  <%- when 0 -%><%= image_tag prod.img, :id => "one") %>
  <%# ... %>
  <%- end -%>
<% end %>

3

这对我解决了空格问题。

<i class="<%
  case blog_post_type
  when :pencil %>fa fa-pencil<%
  when :picture %>fa fa-picture-o<%
  when :film %>fa fa-film<%
  when :headphones %>fa fa-headphones<%
  when :quote %>fa fa-quote-right<%
  when :chain %>fa fa-chain<%
  end
%>"></i>

2
我认为在ERB中,您需要将条件放在`when`标签下面的一行,就像这样:
<% @prods.each_with_index do |prod, index| %>
  <% case index %>
    <% when 0 %>
      <%= image_tag("#{prod}", :id => "one") %>
    <% when 1 %>
      <%=  image_tag("#{prod}", :id => "two") %>
    <% when 2 %>
      <%= image_tag("#{prod}", :id => "three") %>
  <% end %>
<% end %>

Ruby支持使用then关键字的单行条件语句,但我认为ERB无法正确解析它们。例如:

case index
    when 0 then "it's 0"
    when 1 then "it's 1"
    when 2 then "it's 2"
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接