About

How to Use ERB and Partials to Split Views into Reusable Pieces

Writing <%= %> and pulling markup out into partials

ERB syntax:

<%= expression %>   ← output (insert result into HTML)
<% code %>          ← execute only (no output)
<%# comment %>      ← comment
<%== raw_html %>    ← output without HTML escaping

Partial:
View files starting with _.

<%# app/views/posts/_post.html.erb %>
<div class="post">
  <h2><%= post.title %></h2>
  <p><%= post.content %></p>
</div>

<%# Usage %>
<%= render 'post', post: @post %>           <%# single render %>
<%= render partial: 'post', collection: @posts %>  <%# collection render %>
<%= render @posts %>                        <%# shorthand (auto-mapped by convention) %>

Collection rendering renders all at once without repeatedly calling the partial, resulting in better performance.

Key Points

1

<%= %> — output Ruby expression result to HTML (auto-escaped)

2

<% %> — execute Ruby code only (if, each, etc.)

3

Create _partial_name.html.erb (starts with underscore)

4

render "partial_name" or render partial: "name", locals: { ... }

5

render @collection — auto-iterate partial for each item

6

render "shared/header" — render partials from other folders

Pros

  • ✓ Natural Ruby usage within HTML
  • ✓ Code reuse with Partials (DRY)
  • ✓ Performance optimization with collection rendering
  • ✓ Pass data to partials via local variables

Cons

  • ✗ Too many ERB tags reduce readability
  • ✗ Too-small partials complicate file management
  • ✗ Logic in views makes maintenance harder
  • ✗ Need to extract to Helper or Decorator patterns

Use Cases

Common UI fragments (header, footer, navigation) Form partials (shared between new/edit) List item partials Error message partials
← What Is the N+1 Query Problem? Fixing It with includes Rails Layouts and yield: One Shared Frame for Every Page →