Rails rendering partial or block with layout

Rails partials help in breaking HTML into small, reusable chunks of code. To use a partial that yields a block, allowing for dynamic content without code duplication, you can utilize the layout option.

Render Layout with Block

You can render a layout with a block to wrap dynamic content:

<%= render layout: "components/modal" do %>
  <h1>New User</h1>
  <form>...</form>
<% end %>

This will render the _modal.html.erb partial and yield the block content inside it.

Render Layout with Partial

You can also render a partial with a layout:

<%= render partial: "form", layout: "components/modal" %>

This renders the _form.html.erb partial wrapped in the _modal.html.erb layout.

Example Layout File

Here's an example of what your layout partial might look like:

<!-- app/views/components/_modal.html.erb -->
<div class="modal">
  <div class="modal-content">
    <%= yield %>
  </div>
</div>

Benefits

Using layouts with partials provides several benefits:

  • Reduces duplication: Common HTML structure can be reused
  • Better organization: Breaks HTML into smaller, manageable components
  • Flexibility: Allows for dynamic content within consistent layouts
  • Maintainability: Changes to layout structure only need to be made in one place

Conclusion

Rendering partials or blocks with layouts is a powerful Rails feature that helps keep your views DRY and well-organized. It's particularly useful for creating reusable components like modals, cards, or other UI elements.

Rails rendering partial or block with layout - Abhay Nikam