Discover how to stop repeating yourself and make your website easier to build and update!
Why Layouts and content_for in Ruby on Rails? - Purpose & Use Cases
Imagine building a website where every page needs the same header, footer, and sidebar. You have to copy and paste the same HTML into every page file.
Copying the same code everywhere is tiring and risky. If you want to change the header, you must update every page manually. This wastes time and can cause mistakes.
Rails layouts let you define a common page structure once. The content_for method lets you insert unique content into specific parts of the layout easily.
<header>Site Header</header> <p>Page content here</p> <footer>Site Footer</footer>
<!-- layout.html.erb --> <header>Site Header</header> <%= yield %> <footer>Site Footer</footer> <!-- page.html.erb --> <p>Page content here</p>
You can build consistent pages quickly and update shared parts in one place, making your site easier to maintain and grow.
Think of a blog where every post shares the same menu and footer. Using layouts and content_for, you only write the menu once, and each post adds its own title and content.
Layouts provide a shared page structure for all views.
content_for lets you add custom content to layout sections.
This approach saves time and reduces errors when updating your site.