All Articles

Rails rendering partial or block with layout

Rails partials helps breaking the HTML in small reusable chunk of code. I wanted to use partial which yield a block passed so that I can reuse the partial without duplicating the same code multiple times.

Today I learned, in order to use Rails partial with block or dynamic content, we could use layout option.

Example: We may want to render popup modal in the application at multiple places. Modal components content and headers mostly change. We can do it in two different ways:

1. Render layout with block

# apps/views/users/new.html.erb
<%= render layout: "components/modal" do %>
  <h1>New User</h1>
  <form>...</form>
  # Modal content here
<% end %>

2. Render layout with partial

# apps/views/users/new.html.erb
<%= render partial: "form", layout: "components/modal" %>

Please read the Rails documentation on rendering partial with layout.

Happy Coding!!