[Ruby on Rails] How to change title for each page

Tadashi Shigeoka ·  Thu, January 10, 2013

A memo on how to change the title for each page in Ruby on Rails.

■ ERB

<%= content_for?(:title) ? yield(:title) : "default title"%>

■ Haml

%title><
  - if content_for? :title
    = yield :title
    |デフォルトタイトル
  - else
    デフォルトタイトル

You can write meta tag descriptions and keywords in the same way.

■ app/views/layouts/application.html.haml

- if content_for? :meta_description
  - meta_description = yield :meta_description
- else
  - meta_description = 'default description'
%meta(content="#{meta_description}" name="description")
- if content_for? :meta_keywords
  - meta_keywords = yield :meta_keywords
- else
  - meta_keywords = 'default keywords'
%meta(content="#{meta_keywords}" name="keywords")

■ Some view

= content_for :meta_description do
  #{@item.description}
= content_for :meta_keywords do
  #{@item.name}
= content_for :title do
  #{@item.name}

That’s all from the Gemba.