[英]Break out of conditional block in rails
I have to break out of the if condition if the index is greater than 5 after appending the icon in my row. 如果在我的行中附加了图标后索引大于5,则必须打破if条件。 Right now it keeps on adding the icon. 现在,它继续添加图标。
<div class="row sub-navigation">
<% @projects.each_with_index do |project, index| %>
<div class="col-sm-2 col-xs-1">
<% if index > 5 %>
<%= link_to "", path, remote: true, id: "project_div",
class: "glyphicon glyphicon-chevron-down" %>
<% else %>
<%= link_to project.name, project_url(project.project_id), class: ('active' if current_page?(project_path(project.project_id)) ) %>
<% end %>
</div>
<% end %>
</div>
<% @projects.each_with_index do |project, index| %>
<% break if index < 5 %>
<% end %>
-- -
Or you could also use .take
as per this answer : 或者您也可以按照以下答案使用.take
:
<% @projects.take(5).each do |project| %>
...
<% end %>
This will allow you limit the value of the loop to 5 objects only, preventing the need for further logic 这将允许您将循环的值限制为仅5个对象,从而无需进一步的逻辑
break
is a common programming function, designed to get out of a loop break
是一种常见的编程功能,旨在摆脱循环
What Dax
and I were suggesting was to add it along-side your if
statement: 我和Dax
建议的是在if
语句旁边添加它:
<% if index < 5 %>
<% break %>
<% else %>
... do something
<% end %>
If you just want to add an icon for the first 5 links, you'll want to do this: 如果您只想为前5个链接添加图标,则可以执行以下操作:
<% your_class = index > 5 ? nil : "icon_class" %>
<%= link_to "path", path_helper, class: your_class %>
-- -
Update 更新
In response to your pastie, here's what you need to do: 为了响应您的粘贴,这是您需要做的:
<div class="row sub-navigation">
<% @projects.each_with_index do |project, index| %>
<div class="col-sm-2 col-xs-1">
<% your_class = index > 5? "icon_class" : nil %>
<% link_to "", path, remote: true, id: "project_div", class: your_class %>
</div>
</div>
您可以尝试<% break if index > 5 %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.