Rails Application Layout File Overview
Walk through the master layout file for a Ruby on Rails application, this is the shared layout file that the rest of the application starts from.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this lesson, we are going to see how to change the look and feel of our application.

Go to app/views/layouts, and you can see a file called application.html.erb. Open this file, and you'll see that this is our main application view file. So, everything that comes into the application first gets processed through this file. In a Rails application you can even multiple layout files and have the controller dictate which one you want rendered for a particular situation or condition. For this application, and in fact for more than 80 percent of my applications, I have only one application layout file. The DailySmarty application will only use one since all of the pages will share the same header and footer and basic layout options.

If you want to see an example of a site that utilizes multiple layout files, DevCamp uses different layouts throughout the application. For example DevCamp's Homepage uses a promotional layout, whereas the main educational platform itself uses a different layout. In fact, the user profile page uses a third layout option. So in a Rails application you're not limited with how the layout works for different pages.

This is how your application file looks:

large

Now, if I want to play around with it a little bit, I can add some navigation to it. In the body tag, I add

<!-- app/views/layouts/application.html.erb -->

<%= link_to "Home", root_path%>
<%= link_to "About", about_path%>
<%= link_to "Contact", contact_path%>
<%= link_to "Blog", blog_path%>
<%= link_to "Projects", projects_path%>

large

To see the effect of this code on my browser, if I can go to localhost:3000 I can see a link for Home, About, Contact, Blog and Projects at the very top. If I click on any of these links, it will take me to the corresponding page.

small

You may wonder why I'm putting this code in the application file and not in other pages like the About page. This is because when I put it in the About page, these links are available only for that page and not for the entire application. So, I will have to add it to each file, and repeating the same code across different files is not considered to be good programming practice because every time you want to make a change, you have to do it across all pages. This is why I have this navigation code only in my application file.
Next, we'll see how to use partials in our views.