Open In App

Layouts in Ruby on Rails

Last Updated : 18 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Ruby on Rails, a layout is like a template that wraps around your pages. This will give all your web pages an understandable structure so that the header, footer, and the rest of the design look the same on every page. Rails has a default layout named application.html.erb, which can be found in the app/views/layouts folder.

Significance of Layout in Web Application

The layouts in a web application are important for several reasons:

  1. Consistency: The layout creates uniformity across all pages, therefore, each page must provide the same structure. This makes it easy for users to look for something if they know where the key elements are or where to expect other info.
  2. Reusability: Saving time by not needing to repeat code across several pages is another very important reason why using layouts is useful. A single layout can be applied to several views.
  3. Scalability: A centralized layout makes it easier to change individual design elements in one place rather than on each page.
  4. Maintenance: Layouts separate the design elements from the view content, making it easier to modify the design without touching the content.
  5. Code Organization: Organizing code and making it modular is believed to be a better practice as well as easier to handle.

Setting Up Layouts

In Rails, the default layout is application.html.erb, located in the app/views/layouts folder. However, by default, this layout is applied to all views unless one decides otherwise.

Create a Layout

Add a new file in the app/views/layouts/, for example, home.html.erb. And past it.

Example:

app/views/layouts/home.html.erb

HTML
<h1>Welcome to My Rails Application!</h1>
<p>This is your custom welcome page.</p>
<p>Feel free to customize this page!</p>

Use the Layout

Inside your layout (application.html.erb) file, use the yield keyword to declare where your content will show:

HTML
<!DOCTYPE html>
<html>
  <head>
    <title><%= content_for(:title) || "App" %></title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= yield :head %>

    <link rel="manifest" href="/manifest.json">
    <link rel="icon" href="/icon.png" type="image/png">
    <link rel="icon" href="/icon.svg" type="image/svg+xml">
    <link rel="apple-touch-icon" href="/icon.png">
    <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
    <%= javascript_importmap_tags %>
  </head>

  <body>
    <header>Header Content</header>
    <%= yield %>
    <footer>Footer Content</footer>
  </body>
</html>

Using Layouts in Controllers

You can tell a controller to use a specific layout by creating a layout method in app/controllers folder, for example layout_controller.rb:

Ruby
class LayoutController < ApplicationController
  layout "home"
end

Output:

Rails custom home screen Layout
Rails Custom Home Screen Layout

Working with Partials

A partial is a small, reusable piece of code that aids in the structure of code as it is used within a layout. Typical partials are headers, footers, and navigation bars.

  1. Creating a Partial: Partial goes in their respective folders with a file name preceded by an underscore (_), such as _navbar.html.erb .
  2. Rendering a Partial : Utilize render to include the partials in the layout.

Example:

Create a partial file in app/views/layouts/_navbar.html.erb:

Ruby
<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>

Example:

Including a Partial

Ruby
<!DOCTYPE html>
<html>
  <head>
    <title><%= content_for(:title) || "App" %></title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= yield :head %>

    <link rel="manifest" href="/manifest.json">
    <link rel="icon" href="/icon.png" type="image/png">
    <link rel="icon" href="/icon.svg" type="image/svg+xml">
    <link rel="apple-touch-icon" href="/icon.png">
    <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
    <%= javascript_importmap_tags %>
 
  </head>

  <body>
    <header>Header Content</header>
    <div class="container">
      <div class="main-content">
        <%= yield %>
      </div>
        
      <%= render 'layouts/navbar' %>
      
    </div>
    <footer>Footer Content</footer>
  </body>
</html>

Output:

Rails Partial view
Rails Partial View

Content_for Layouts

Rails uses yield and content_for to add content within layouts.

  1. Yield: Here's where the main page content would go.
  2. Content: It lets you put specific content in other parts of the layout, whether that's in the sidebar or the header.

Example:

Using content_for, in your view you can define specific content:

Ruby
<% content_for :sidebar do %>
  <p>Sidebar Content</p>
<% end %>

In the layout, you render the sidebar content like this:

<%= yield :sidebar %>

Layouts and Views

Layouts provide the general structure, and views provide the content. When you request a page, Rails combines the layout with the view. If you need to render a view without using a layout, you can do so with:

render layout: false

Dynamic Layouts

You can change the layouts dynamically depending on the situation. For example, you may want different layouts for users and admins. This can be achieved using conditional logic in your layout controllers.

Ruby
class ApplicationController < ActionController::Base
  layout :layout_by_resource
  
  private

  def layout_by_resource
    if user_signed_in? && current_user.admin?
      "admin"  # Use admin layout
    else
      "application"  # Use default layout
    end
  end
end

Debugging Layouts

If your layout isn’t displaying as expected, check the following:

  1. Ensure you are specifying the correct layout in the controller.
  2. Verify that you are using yield and content_for correctly.
  3. Check the Rails development log to see how layouts are being rendered.

Best Practices of Layouts

  1. Keep It Simple: Do not over-include code in the layout. Use partials to keep things organized.
  2. Use Partials for Components: Put commonly reused elements, such as headers and footers, in partials to make it more modular.
  3. Optimize the loading scripts: Place scripts at the bottom of a layout in order to load faster.
  4. Minimize inline CSS and JS: Move CSS and JS code to different files, thus avoiding the clutter that these layouts might trigger and will enjoy a better caching.
  5. Accessibility by Design: Semantic HTML with ARIA labels to make content accessible to everyone.

Conclusion

Layouts in Rails keep everything consistent throughout all of your pages. Layouts make an application easier to maintain by reusing code and, when used with stylesheets, can really help towards giving a polished and professional website in appearance.


Next Article
Article Tags :

Similar Reads