0
0

More than 1 year has passed since last update.

Railsでタイトルをページごとに変化させて表示させたい

Posted at

titleをページごとに変化させて表示させたい

・イメージとしては『移動先のページタイトル | 固定タイトル』のようにしたい

・アクセスした時ページは『移動先のページタイトル | 固定タイトル』の『移動先のページタイトル|』はいらないので固定タイトルのみ表示させたい

カスタムヘルパーを作成

app/helper/application.rb下

def page_title(page_title = '')
  base_title = '固定ページ名' 

  page_title.empty? ? base_title : page_title + " | " + base_title
end

そしてview/layout/application.html.erbの

内の内に
<%= page_title(yield(:title)) %>

と先ほど作成したヘルパーを使用し、webページ全体に適用させる

そして各viewページで

<%= content_for(:title, t('.title')) %>

と埋め込むことで:titleにviewファイルで設定しているページ名が渡され、page_titleメソッドの引数にわたされるため『移動先のページタイトル | 固定タイトル』と表示できるようになる。

ちなみにviewファイルのt('.title')は事前にconfig/locales/view/ja.ymlに翻訳を登録しておくと良い。ユーザー登録画面のタイトルを翻訳するなら

config/locales/view/ja.yml下

users:
    new:
      title: 'ユーザー登録'

こうすることでusers/newにアクセスした時にt('.title')がユーザー登録と翻訳される。

0
0
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
0
0