Rails相当于Laravel的 $loop->first

后端开发 2026-07-12

在Laravel中,当遍历一组事物,比如文章/帖子时,你可以用if语句来检查 if($loop->first),以查看当前项是否是数组中的第一项。然后你可以据此为第一项使用一个不同的UI组件,余下的项再排成网格之类的布局。

Rails的做法是怎样的?

一个更好的示例,说明你可能会这样使用它:

@foreach($items as $item)
    @if($loop->first)
    Make the first item look different
    @else
        render the rest of the items as a list
    @endif
@foreach

解决方案

在Rails的 ERB模板中,你会使用 each_with_indexeach.with_index 来跟踪位置:

<% @items.each_with_index do |item, index| %>
  <% if index == 0 %>
    <!-- Make the first item look different -->
  <% else %>
    <!-- render the rest of the items as a list -->
  <% end %>
<% end %>

或者如果你只是需要在循环前把第一项和剩下的项分开,可以使用 each_with_object / Ruby内置的 first

<% @items.first.tap do |item| %>
  <!-- featured item -->
<% end %>

<% @items.drop(1).each do |item| %>
  <!-- rest as a list -->
<% end %>

第二种方式通常更干净,因为它完全避免了循环内的条件——你只需要单独处理第一项,然后遍历剩余项。这与你描述的“hero + grid”UI模式相当自然。

如果你使用ViewComponents或 partials,你也可能会看到这种模式:

<%= render FeaturedComponent.new(item: @items.first) %>
<%= render partial: "item", collection: @items.drop(1) %>
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章