Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to change the title of a page?

In your views do something like this:

<% content_for :title, "Title for specific page" %>
<!-- or -->
<h1><%= content_for(:title, "Title for specific page") %></h1>

The following goes in the layout file:

<head>
  <title><%= yield(:title) %></title>
  <!-- Additional header tags here -->
</head>
<body>
  <!-- If all pages contain a headline tag, it's preferable to put that in the layout file too -->
  <h1><%= yield(:title) %></h1>
</body>

It's also possible to encapsulate the content_for and yield(:title) statements in helper methods (as others have already suggested). However, in simple cases such as this one I like to put the necessary code directly into the specific views without custom helpers.


Here's a simple option that I like to use

In your layout

<head>
  <title><%= @title %></title>
</head>

And at the top of your page template (first line)

<% @title="Home" %>

Because of the way the layout and page templates are parsed the @title="Home" is evaluated before the layout is rendered.


Best practice is to use content_for.

First, add a couple of helper methods (ie. stick in app/helpers/application_helper.rb):

def page_title(separator = " – ")
  [content_for(:title), 'My Cool Site'].compact.join(separator)
end

def page_heading(title)
  content_for(:title){ title }
  content_tag(:h1, title)
end

Then in your layout view you can simply use:

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

...and in the view itself:

<%= page_heading "Awesome" %>

This way has the advantage of allowing you to shuffle where you stick the h1 tag for your title, and keeps your controller nice and free of pesky @title variables.


An improvement on @opsb and a more complete form of @FouZ's:

In application.html.erb:

<title><%= @title || "Default Page Title" %></title>

In the view erb file or its controller:

<% @title = "Unique Page Title" %>

Look into content_for: http://railscasts.com/episodes/8


Without further details on the use-case or requirements that you're trying to satisfy, I can think of several alternatives:

1) Switch the title in one of your layout pages and consume a helper method stored in application_helper.rb

<title><%= custom_title %></title>

This approach will give you a unique title for each layout page.

2) Railscasts suggests using a partial to load what shows up between the HEAD tags

3) Use javascript/ajax calls to manipulate the DOM if you need to change the title after the load event.

Maybe you don't really want to change the content tagged by the title element. Perhaps you really need a breadcrumb of some sort, so that your users always know where they are with respect to your site's navigation hierarchy. While I've done fine with how the goldberg plugin, I'm sure there are other ways of pulling off the same functionality.