Reducing Maintenance with Layouts

Learn to maintain our application using Rails layouts.

So far in this chapter, we’ve looked at templates as isolated chunks of code and HTML. One of the driving ideas behind Rails is honoring the DRY principle and eliminating the need for duplication. The average website, though, has lots of duplication:

  • Many pages share the same tops, tails, and sidebars
  • Multiple pages may contain the same snippets of rendered HTML (a blog site, for example, may display an article in multiple places)
  • The same functionality may appear in multiple places. Many sites have a standard search component or a polling component that appears in most of the sites’ sidebars

Rails provides both layouts and partials that reduce the need for duplication in these three situations.


Rails allows us to render pages that are nested inside other rendered pages. Typically this feature is used to put the content from an action within a standard site-wide page frame (title, footer, and sidebar). In fact, if we’ve been using the generate script to create scaffold-based applications, then we’ve been using these layouts all along.

When Rails honors a request to render a template from within a controller, it actually renders two templates. Obviously, it renders the one we ask for (or the default template named after the action if we don’t explicitly render anything). Rails also tries to find and render a layout template. We’ll talk about how it finds the layout in a second. If it finds the layout, it inserts the action-specific output into the HTML produced by the layout.

Let’s look at a layout template:

Let’s look at a layout template:

Get hands-on with 1200+ tech skills courses.