Ruby on Rails / Views and Templates

Using Layouts and Partials for Code Reuse

In this tutorial, you'll learn how to use layouts and partials to promote code reuse in your Rails applications. We'll cover how to create and use these features to keep your code…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Teaches how to create dynamic views using ERB and layouts in Rails.

Using Layouts and Partials for Code Reuse in Rails

1. Introduction

Goal

This tutorial aims to teach you how to use layouts and partials in Rails to promote code reuse, keeping your code DRY (Don't Repeat Yourself) and maintainable.

Learning Outcomes

By the end of this tutorial, you'll be able to:
- Understand the concepts of layouts and partials in Rails.
- Create and use layouts and partials.
- Apply layouts and partials to promote code reuse.

Prerequisites

A basic understanding of Ruby on Rails, MVC architecture, and HTML is recommended.

2. Step-by-Step Guide

Concepts

Layouts in Rails are templates that encapsulate the HTML that wraps your views. They are used to maintain consistency in your app's look and feel.

Partials, on the other hand, are smaller chunks of view code that can be used across different views. They are a great way to keep your views DRY and organized.

Using Layouts

By default, Rails uses the application layout (app/views/layouts/application.html.erb). If you want a different layout for a specific controller, you can define it in the controller like this:

class PagesController < ApplicationController
  layout 'custom'
end

This will tell Rails to use app/views/layouts/custom.html.erb for all views in the PagesController.

Using Partials

Partials are named with a leading underscore to distinguish them from regular views. To render a partial within a view, you can use the render method:

<%= render 'shared/menu' %>

This will include the contents of app/views/shared/_menu.html.erb.

3. Code Examples

Layout Example

<!-- app/views/layouts/custom.html.erb -->
<!DOCTYPE html>
<html>
<head>
  <title>Custom Layout</title>
  <%= csrf_meta_tags %>
  <%= csp_meta_tag %>

  <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
  <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
  <%= yield %>
</body>
</html>

This is a basic custom layout. The <%= yield %> line is where the view for the current action will be inserted.

Partial Example

<!-- app/views/shared/_menu.html.erb -->
<nav>
  <ul>
    <li><%= link_to 'Home', root_path %></li>
    <li><%= link_to 'About', about_path %></li>
    <li><%= link_to 'Contact', contact_path %></li>
  </ul>
</nav>

This is a simple navigation menu. You can include it in any view or layout with <%= render 'shared/menu' %>.

4. Summary

We've covered the basics of using layouts and partials in Rails, including how to create them and how to include them in your views. These techniques can help you keep your views DRY and consistent.

For further learning, consider exploring more complex use cases for partials, such as passing local variables or collections.

5. Practice Exercises

  1. Create a layout that includes a header, footer, and a sidebar. Use this layout for a new controller.
  2. Create a partial that displays a list of posts. Use this partial in multiple views.
  3. Pass a local variable to a partial and use it to change the partial's behavior.

Solutions

  1. This is a fairly straightforward exercise. Just create the layout file and include the desired elements. Then, specify the layout in your new controller with the layout method.
  2. To create the posts partial, you'll need to loop through a collection of posts. You can then render this partial in any view where you have a collection of posts.
  3. To pass a local variable to a partial, you can use the :locals option with the render method: <%= render 'shared/menu', locals: { special_item: @special_item } %>. Inside the partial, you can use the special_item variable as if it were defined in the partial.

Remember to practice regularly and experiment with different layouts and partials to get the most out of these features. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help