rails page titles

Viewed 15864

I don't like the way rails does page titles by default (just uses the controller name), so I'm working on a new way of doing it like so:

application controller:

def page_title
    "Default Title Here"
end

posts controller:

def page_title
    "Awesome Posts"
end

application layout:

<title><%=controller.page_title%></title>

It works well because if I don't have a page_title method in whatever controller I'm currently using it falls back to the default in the application controller. But what if in my users controller I want it to return "Signup" for the "new" action, but fall back for any other action? Is there a way to do that?

Secondly, does anyone else have any other ways of doing page titles in rails?

6 Answers
class ApplicationController < ActionController::Base
  before_action :set_page_title

  private

  def set_page_title
    @page_title = t(".page_title", default: '').presence || t("#{controller_name}.page_title", default: '').presence || controller_name.titleize
  end
end

I recently started taking this approach then outputting @page_title in the layout. It seems to work quite nicely for me.

Related