Page Titles in Rails Apps

Menu

Giving meaningful titles to the views of your Rails Application is a nice touch you can easily add to your Rails application.

The most popular approach on StackOverflow seems to be that of defining a @title variable in the controller, which can then be used in the application layout (See, for instance ("Rails 3 - Ideal Way to Set the Title of Pages). The approach is nice and flexible, since each screen can have its own meaningful title, but it can be a pain, if your application has many screens, since you need to set the variable for each controller and each method of your controller.

A simpler and faster approach exploits the fact Rails has a method to get the name of the active controller and that the active controller gives a good indicator of what the current view does.

Put in application_helper.rb something like:

def page_title
  controller_name.capitalize + " | GasApp"
end

and use it in the <title> tag of your application’s layouts:

<title><%= page_title %></title>

This will give a pretty good hint on the current the current view.

For instance:

(… and if you are wondering, I first tried with the GasApp.)