What is the best way to create a custom title for pages in a Rails app without using a plug-in?
This simple approach sets a default title, but also let you override it whenever you please.
In app/views/layouts/application.html.erb
:
<title><%= yield(:title) || 'my default title' %></title>
And to override that default, place this in any view you like
<% content_for :title, "some new title" %>
You can also set it in a before_filter in your controller.
# foo_controller.rb
class FooController < ApplicationController
before_filter :set_title
private
def set_title
@page_title = "Foo Page"
end
end
# application.html.erb
<h1><%= page_title %></h1>
You can then set conditions in the set_title method to set a different titles for different actions in the controller. It's nice to be able to see all the relevant page titles within your controller.
In short, I can write this down as follow
<%content_for :page_title do %><%= t :page_title, "Name of Your Page" %> <% end %>