Page Titles in Rails Apps

Giving meaningful page titles to distinguish different views 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.

I much simpler and faster way exploits the fact Rails has a method to get the name of the active controller and that the active controller gives a good indication of the current view.

Thus, if you put in application_helper.rb something like:

def page_title
  controller_name.capitalize + " | GasApp"

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

This can give a pretty good hint on the current page the user is looking at. For instance:

  • Users | GasApp will be the title of pages generated by a method of the users controller, that is, the list of all users.
  • Purchases | GasApp, will be the title of pages generated by any method of the purchases controller

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

Get in touch