Layouts help you keep a common look for many pages.
content_for lets you add special parts to that layout from each page.
0
0
Layouts and content_for in Ruby on Rails
Introduction
You want all pages to share the same header and footer.
You need to add a custom title or script on some pages only.
You want to keep your HTML organized and avoid repeating code.
You want to insert extra content like ads or banners in specific pages.
You want to separate page-specific content from the main layout.
Syntax
Ruby on Rails
In layout file (e.g., application.html.erb): <%= yield %> <!-- main content --> <%= yield :sidebar %> <!-- named content --> In view file: <% content_for :sidebar do %> <p>Sidebar content here</p> <% end %>
yield shows the main content from views.
content_for defines extra content blocks you can place anywhere in the layout.
Examples
This layout shows header and footer around the main page content.
Ruby on Rails
<!-- layout.html.erb -->
<html>
<body>
<header>Site Header</header>
<%= yield %>
<footer>Site Footer</footer>
</body>
</html>This layout adds a sidebar area that can be filled by views using
content_for :sidebar.Ruby on Rails
<!-- layout.html.erb -->
<html>
<body>
<header>Site Header</header>
<%= yield %>
<aside>
<%= yield :sidebar %>
</aside>
<footer>Site Footer</footer>
</body>
</html>This view fills the sidebar block defined in the layout.
Ruby on Rails
<!-- view.html.erb --> <h1>Welcome</h1> <p>Main page content.</p> <% content_for :sidebar do %> <p>Links and info for sidebar.</p> <% end %>
Sample Program
This example shows a layout with a dynamic title and footer. The home page view sets a custom title and footer content using content_for. The main content appears in the <main> area.
Ruby on Rails
<!-- app/views/layouts/application.html.erb --> <html lang="en"> <head> <title><%= content_for?(:title) ? yield(:title) : "Default Title" %></title> </head> <body> <header> <h1>My Website</h1> </header> <main> <%= yield %> </main> <footer> <%= yield :footer %> </footer> </body> </html> <!-- app/views/home/index.html.erb --> <% content_for :title do %> Home Page <% end %> <h2>Welcome to the Home Page</h2> <p>This is the main content area.</p> <% content_for :footer do %> <p>Contact us at contact@example.com</p> <% end %>
OutputSuccess
Important Notes
If you don't use content_for for a named yield, it will show nothing.
Use content_for? to check if content exists before showing it.
Layouts keep your site consistent and easy to update.
Summary
Layouts wrap your pages with shared HTML like headers and footers.
content_for lets views add special content to named spots in layouts.
This helps keep your code clean and your site consistent.