Reducing Maintenance with Layouts
Explore how Rails layouts and partials reduce duplication in web pages by sharing common elements like headers, footers, and sidebars. Understand layout rendering, dynamic layouts, and passing data between templates and layouts to streamline your application maintenance.
We'll cover the following...
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.
Layouts
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 ...