Easy Dynamic Page Titles in Rails

Aug 09, 2006

While even I get lazy about it sometimes, it is important to try to give each page on your site a unique page title. This makes them easy to bookmark and easy for Google to index them. So why this is an issue in Rails? Because layouts are great way to keep your application elegant and stick to the DRY principle.

So you have a layout that contains the common elements of each page on your site: the header, footer, sidebar, etc, etc. It also contains the <title> tags so each page will have the same title if this is just a static string. For Example:

<html>
<head>
    <title>My Great Site</title>
</head>

<body>

    <%= @content_for_layout %>

</body>
</html>

So you want this title to not be static, but instead dynamic so each page will get it’s own unique title instead of just “My Great Site”. We rather have it say something like “My Great Site: Biography” were our visitors on the Biography page.

The Hard Way

So you could just give each controller action a @page_title variable and set that to whatever you want the page title to be. So you’d have:

<title>My Great Site: <%= @page_title %></title>

This of course is a pain in the butt because you have to do this for every single action. Not fun if you have a ton of pages.

The Easy Way

Since most Rails developers like descriptive URLs and use the power of custom routes why not just have your controller action be part of the page title? This way we don’t have to worry about extra variables and just use the information already available to us.

<title>My Great Site: <%= params[:action].capitalize %></title>

So our “biography” action gives us a page title of “My Great Site: Biography”.

Simple, easy, and solves our problem nicely.