0
0
RailsHow-ToBeginner · 3 min read

How to Use Partials in Rails: Syntax and Examples

In Rails, use render partial: 'partial_name' or simply render 'partial_name' to include reusable view snippets called partials. Partials help keep views clean by extracting repeated HTML into separate files prefixed with an underscore.
📐

Syntax

Partials are small view templates stored in the app/views folder with filenames starting with an underscore (_). To include a partial in another view, use the render method.

  • render 'partial_name': Renders the partial named _partial_name.html.erb from the current controller's view folder.
  • render partial: 'partial_name': Explicit syntax for rendering the partial.
  • render partial: 'folder/partial_name': Renders a partial from a subfolder.
  • render partial: 'partial_name', locals: { key: value }: Passes local variables to the partial.
erb
<%= render 'shared/header' %>
<%= render partial: 'comments/comment', locals: { comment: @comment } %>
💻

Example

This example shows how to create and use a partial to display a comment. The partial receives a local variable comment and displays its content.

erb
<!-- app/views/comments/_comment.html.erb -->
<p><strong><%= comment.author %>:</strong> <%= comment.body %></p>

<!-- app/views/comments/index.html.erb -->
<h2>Comments</h2>
<%= render partial: 'comment', collection: @comments %>
Output
<h2>Comments</h2> <p><strong>Alice:</strong> Great post!</p> <p><strong>Bob:</strong> Thanks for sharing.</p>
⚠️

Common Pitfalls

  • Forgetting the underscore (_) in the partial filename will cause Rails not to find the partial.
  • Not passing required local variables to the partial can cause errors or missing data.
  • Using render 'partial_name' without specifying the folder when the partial is in a different folder leads to missing partial errors.
  • Confusing render partial: 'name' with rendering a full template; partials are meant for reusable snippets only.
erb
<!-- Wrong: missing underscore in filename -->
<!-- Filename: comment.html.erb instead of _comment.html.erb -->
<%= render 'comment' %>

<!-- Right: correct filename -->
<!-- Filename: _comment.html.erb -->
<%= render 'comment' %>
📊

Quick Reference

Use these tips to work effectively with Rails partials:

  • Partial filenames start with an underscore, e.g., _menu.html.erb.
  • Use render 'partial_name' to include partials.
  • Pass variables with locals: { key: value }.
  • Use collection: to render a list of partials for an array.
  • Keep partials focused on small reusable pieces of UI.

Key Takeaways

Partials are reusable view snippets stored with filenames starting with an underscore.
Use render 'partial_name' or render partial: 'partial_name' to include partials in views.
Pass data to partials using the locals option to keep them flexible.
Always name partial files with a leading underscore to avoid missing partial errors.
Use partials to keep your views clean and DRY by extracting repeated HTML.