【问题标题】:Rails switch case in the view视图中的 Rails 开关盒
【发布时间】:2012-03-25 02:09:05
【问题描述】:
我想在我的视图中写一个开关盒:
<% @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 %>?有任何想法吗 ?
谢谢!
【问题讨论】:
标签:
ruby-on-rails
view
switch-statement
【解决方案1】:
您应该将您的第一个 when 拉到与 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 %>
【解决方案2】:
不要在你的观点中加入太多逻辑。
我会添加一个助手
def humanize_number(number)
humanized_numbers = {"0" => "zero", "1" => "one"}
humanized_numbers[number.to_s]
end
你可以从视图中调用它
<%= image_tag("#{prod.img}", :id => humanized_number(index)) %>
【解决方案3】:
首先,您应该真正考虑将此功能抽象为辅助方法,以避免逻辑混乱您的视图。
其次,在 ERB 中使用 case 语句有点棘手,因为 erb 解析代码的方式。改为尝试(未测试,因为我手头没有红宝石):
<% @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 %>
请参阅this 线程了解更多信息。
【解决方案4】:
你也可以使用<%- case index -%>语法:
<% @prods.each_with_index do |prod, index| %>
<%- case index -%>
<%- when 0 -%><%= image_tag prod.img, :id => "one") %>
<%# ... %>
<%- end -%>
<% end %>
【解决方案5】:
这对我来说有助于空白。
<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>
【解决方案6】:
我认为在 ERB 中,您必须在 whens 下设置条件。像这样:
<% @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 关键字的单行条件的 case-whens,但我认为 ERB 不能正确解析它们。例如:
case index
when 0 then "it's 0"
when 1 then "it's 1"
when 2 then "it's 2"
end