LoginSignup
9
8

More than 5 years have passed since last update.

RailsでページのタイトルをI18nを使って変更する方法

Last updated at Posted at 2015-01-03

1. 概要

Railsでページのタイトルを変更する方法としては、独自にヘルパーメソッドを追加する方法などがあるが、ここではtitleizerというGemを使った方法を示す。

2. インストール

Gemfileに以下を追加し、bundle installする。

Gemfile
gem 'titleizer'

3. 使い方

基本的な使い方

1) タイトルを設定する

config/locales/*.ymlに、以下のようにタイトルを設定する(例えばtitle.ja.yml)。

config/locales/title.ja.yml
ja:
  title:
    application: サンプルブログ
    description: これはサンプルブログです
    posts:
      index: 記事一覧
      show: "%{subject}"
      new: 記事投稿
      edit: 記事編集
          :

2) タイトルタグを編集する

app/views/layouts/application.html.erbのタイトルタグを次のように編集する。

app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title><%= title(yield :title) %></title>
        :
  </head>

以上で、コントローラとアクションに応じたタイトルが自動でタイトルタグに設定される。
例えば、上記設定ではタイトルは以下のようになる。

パス タイトル
root_path これはサンプルブログです | サンプルブログ
posts_path 記事一覧 | サンプルブログ

オプション

変数を使用する

例えばtitle.ja.yml内の%{subject}など、タイトルに変数を使用したい場合がある。
この場合、コントローラのアクション内で@title_paramsに変数をセットできる。

app/controllers/posts_controller.rb
class PostsController < ApplicationController
  def show
    @post = Post.find(params[:id])

    @title_params = { subject: @post.subject }
  end
end

タイトルを上書きする

例えばエラーページなど、title.ja.yml内で設定したタイトルとは違うタイトルを設定したい場合がある。
この場合、ビューでprovide :titleにより上書きできる。

app/views/shared/_render_404.html.erb
<% provide :title, '404 Not Found' %>

4. 参考

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8