How to Render Partial in Rails: Syntax and Examples
In Rails, you render a partial using
render partial: 'partial_name' or simply render 'partial_name'. Partials are reusable view templates that help keep your code DRY and organized.Syntax
Use render partial: 'partial_name' or the shorthand render 'partial_name' to include a partial view. The partial file should start with an underscore, like _partial_name.html.erb.
You can also pass local variables with locals: { key: value } to customize the partial.
erb
<%= render partial: 'shared/header' %> <%= render 'shared/header' %> <%= render 'shared/item', locals: { item: @item } %>
Example
This example shows rendering a partial named _greeting.html.erb that displays a greeting message. The partial receives a local variable name.
erb
<!-- app/views/home/index.html.erb --> <h1>Welcome Page</h1> <%= render 'greeting', locals: { name: 'Alice' } %> <!-- app/views/home/_greeting.html.erb --> <p>Hello, <%= name %>! Welcome to our site.</p>
Output
<h1>Welcome Page</h1>
<p>Hello, Alice! Welcome to our site.</p>
Common Pitfalls
- Forgetting the underscore prefix in the partial filename (e.g., use
_partial.html.erb, notpartial.html.erb). - Not passing required local variables, causing errors inside the partial.
- Using
render partial:with a full path but missing the underscore. - Trying to render a partial without the correct file extension.
erb
<!-- Wrong: missing underscore --> <%= render 'header' %> <!-- Will fail if file is named header.html.erb instead of _header.html.erb --> <!-- Right: with underscore --> <%= render 'header' %> <!-- Works if file is _header.html.erb -->
Quick Reference
Tips for rendering partials in Rails:
- Partial filenames start with an underscore.
- Use
render 'partial_name'for simplicity. - Pass variables with
locals: { key: value }. - Keep partials small and focused for reuse.
Key Takeaways
Render partials with
render 'partial_name' where the file starts with an underscore.Pass data to partials using
locals: { key: value } to customize content.Always name partial files with a leading underscore to be recognized by Rails.
Keep partials focused and reusable to maintain clean views.
Avoid missing underscores or forgetting to pass required locals to prevent errors.