๐
ERB & Partials
Embed Ruby in HTML and split into reusable fragments
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