How to Use content_for in Rails: Syntax and Examples
In Rails,
content_for lets you define named content blocks in views that you can render later in layouts using yield. Use content_for :name do ... end to set content and yield :name in the layout to display it.Syntax
The content_for method defines a named content block inside a view. You write content_for :block_name do ... end to capture content. In the layout, use yield :block_name to render that content where you want it.
This helps you insert specific content like scripts, styles, or page titles from views into the layout.
erb
<%= content_for :sidebar do %>
<p>This is sidebar content.</p>
<% end %>
<!-- In layout file -->
<%= yield :sidebar %>Output
<p>This is sidebar content.</p>
Example
This example shows how to set a page title and a sidebar content in a view, then render them in the layout.
erb
<!-- app/views/articles/show.html.erb --> <% content_for :title do %> Article Details <% end %> <% content_for :sidebar do %> <p>Related Articles</p> <% end %> <h1>Article Content Here</h1> <!-- app/views/layouts/application.html.erb --> <html> <head> <title><%= yield(:title) || "Default Title" %></title> </head> <body> <div class="sidebar"> <%= yield :sidebar %> </div> <div class="main"> <%= yield %> </div> </body> </html>
Output
<html>
<head>
<title>Article Details</title>
</head>
<body>
<div class="sidebar">
<p>Related Articles</p>
</div>
<div class="main">
<h1>Article Content Here</h1>
</div>
</body>
</html>
Common Pitfalls
- Forgetting to use
yield :block_namein the layout means the content won't show. - Using
content_forwithout a block or with incorrect syntax causes errors. - Trying to use
content_foroutside views (like controllers) won't work. - Overwriting content_for blocks unintentionally by calling it multiple times with the same name replaces previous content.
erb
<!-- Wrong: no yield in layout, content_for block won't display --> <% content_for :footer do %> <p>Footer info</p> <% end %> <!-- layout missing: <%= yield :footer %> --> <!-- Right: add yield in layout --> <%= yield :footer %>
Quick Reference
content_for usage:
content_for :name do ... end- Define content block named:name.yield :name- Render the named content block in layout.- Use for titles, scripts, styles, sidebars, or any layout-specific content.
Key Takeaways
Use
content_for :name do ... end in views to define content blocks.Render these blocks in layouts with
yield :name to insert content.Always ensure the layout includes
yield :name or content won't appear.Avoid overwriting content_for blocks unintentionally by calling them multiple times with the same name.
content_for works only inside views, not in controllers or helpers.