AbstractBrain Answers About us

How to set the page title in Ruby on Rails


What is the correct way to set the page title in Rails?

In a Ruby on Rails application, what is the recommended way to set the page title?

For example, in the application layout you have:

<title>My Website</title>

How do you change the title based on the current page? 

Is there an automatic / simple way to set the page title to the main page heading (e.g. h1)?


The easiest solution for setting a title in a Rails application is to define an ApplicationHelper inside app/helpers/application_helper.rb:

def title t
  content_for :title, t

Then inside the application layout you can use:

<title><%= yield(:title) + ' - ' if content_for?(:title) %>MyWebsite</title>

If the title is set for that page, it displays it, otherwise you display only the name of the website (e.g. MyWebsite).

Then in your views you can easily set the title:

<h1><%= title('Welcome to MyWebsite!') %></h1>

If you need to set a title different from the page heading, you can also set it separately. For example:

<% title 'Home' %>
<h1>Welcome to MyWebsite!</h1>