Adding a Title in Rails

By | 14/12/2015

After moving the contents of <head>…</head> to a partial you can add a title dynamically to each page.

To get the title to render you need to add

<title><%= full_title(yield(:title)) %></title>

to the <head> and you can then add the title to each page with the

<% provide title: "Title Here" %>.
which adds the title of each page to the base title.

Refactoring the code we can add a method to the application_helper file to render the title on each page.

def full_title(page_title = '')
  base_title = "My Rails App"
  if page_title.empty?
    "#{page_title} | #{base_title}"

If no title is provided on the page the base title will just show on its own.