Member-only story

Rails Layout Rendering Cheatsheet

Kevin Kim
2 min readJul 29, 2018

--

Layout Logic

Rails uses a simple convention to find the correct layout for your request. If you have a controller called ProductsController, Rails will see whether there is a layout for that controller under views/layouts/products.html.erb. If it can’t find a layout specific to your controller, it’ll use the default layout at views/layouts/application.html.erb.

A typical Rails app created from the new rails project command will produce the following in the views/layouts/application.html.erb.

<!DOCTYPE html>
<html>
<head>
<title>Your project</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %></body>
</html>

Any page specific content i.e. (from a show, index, edit route) will be yielded after an appropriate layout has been chosen.

Overriding Conventions

1. Override layout for every action in a given controller

class ShoppingCartController < ApplicationController
layout "products"
def index
end
def show
end

...
end

Instead of looking for a layout at layouts/shopping_carts.html.erb and if it fails to…

--

--

No responses yet