Quick tip: Using Partials to Simplify Views
Sometimes you want to have multiple views that share HTML (and render different content only deep inside the block of HTML).
For example, modals, multi-step forms, or a wizard:
Not to duplicate HTML, use Partials to Simplify Views. With yield
and do
-blocks.
Before: #
# new.html.haml
<div class="modal">
<div class="modal-header">
New post
</div>
<div class="modal-body">
<%= render "form", post: @post %>
</div>
</div>
# edit.html.haml
<div class="modal">
<div class="modal-header">
Edit post
</div>
<div class="modal-body">
<%= render "form", post: @post %>
</div>
</div>
After: #
# shared/_modal.html.haml
<div class="modal">
<div class="modal-header">
<%= title %>
</div>
<div class="modal-body">
<%= yield %>
</div>
</div>
# new.html.haml
<%= render "shared/modal", title: "New post" do %>
<%= render "form", post: @post %>
<% end %>
# edit.html.haml
<%= render "shared/modal", title: "Edit post" do %>
<%= render "form", post: @post %>
<% end %>
Much cleaner, isn’t it?! ;)
It is also very common to use ViewCompoenent for doing exactly this (rendering content inside an HTML block)!
= render layout: ‘courses/course_wizard/step’ do
Did you like this article? Did it save you some time?