Rails: how to make a layout around a collection?

Rails supports the parameter :layoutwhen rendering the partitions of the collection, but the layout applies to each element in the list.

Is there any way to add a layout around the entire collection?

More details

Say I have a collection @promoted_stories. I want to display some HTML around the rendered collection, but only if @promoted_storiesnot empty. What I want can be achieved as follows:

<% if @prometed_stories.present? %>
<div class="promoted-stories>
  <%= render @promoted_stories %>
</div>
<% end %>

Can I do the same and avoid if? I am a fan of logic layouts, so I would like to avoid as much branching as possible in my views. I would prefer if something like this is possible:

# View:
<%= render collection: @promoted_stories, collection_layout: 'promoted_stories' %>

# _promoted_stories.html.erb
<div class="promoted-stories">
  <%= yield %>
</div>
+4
source share
1

, , :

# Helper
def render_collection_template(template, collection)
  render template: "layouts/#{template}", locals: { collection: collection } if collection.present?
end

# View
<%= render_collection_template 'promoted_stories', @promoted_stories %>

# Template
<div class="promoted-stories">
  <%= render collection %>
</div>

pull request , .

+3

All Articles