how to use “render :partial”

“Partial Templates” (aka. “partials”) is a way for breaking down the rendering process into more simplified and manageable chunks. Think of it as a placeholder for a piece of the webpage that is stored in another file. The partial command calls for the other file to be rendered in the response.

Calling a partial is coded as follows:

1
<%= render :partial => "menu" %>

This command would call for _menu.html.erb to be rendered where the above code is inserted. All partial view files are named with a leading underscore _XXX to distinguish partials from regular view files.

During the Intermedia Homework assignment, the view/index.html.erb file used a partial to render the collection of the groups model, displaying information for each member of the group:

index.html.erb
1
2
<%= render :partial => "group_item", :collection => @groups, :as => :group %>

With the partial code:

_group.item.html.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
<tr>
<td>#</td>
<td><%= link_to(group.title, group_path(group)) %></td>
<td><%= render_group_description(group) %></td>
<td><%= group.user.email %></td>
<td>
<% if current_user && current_user == group.user %>
<%= link_to("Edit", edit_group_path(group), class: "btn btn-sm btn-default")%>
<%= link_to("Delete", group_path(group), class: "btn btn-sm btn-default",
method: :delete, data: { confirm: "Are you sure?" } )%>
<% end %>
</td>
</tr>

This displays a table showing each group, which works similarly as the <% @groups.each do |f| %> function.