LoginSignup
1
0

More than 1 year has passed since last update.

【Rails】ページ毎にタイトルを変更する方法

Last updated at Posted at 2022-01-04

content_forを使ってタイトル名を変えていく

content_forというヘルパーを使って
「 ページ名 | 固定タイトル 」
と出力するやり方を見ていく。

手順
app/helpers/application_helperにヘルパーメソッドを記入
views/layouts/applicationにメソッドを記入
③viewにそれぞれのタイトルを入れていく

app/helpers/application_helperにヘルパーメソッドを記入

app/helpers/application_helper.rb
module ApplicationHelper
    def page_title(page_titlle = '')
        base_title = 'SAMPLE BOARD APP'
        
        page_title.empty? ? base_title : page_title + ' | ' + base_title
    end
end

page_title.empty? ? base_title : page_title + ' | ' + base_title
この一文は見慣れないが、条件演算子(三項演算子)を使った書き方となっている。
この一文をif分に書き換えると下記のようになる。

if page_title.empty?
  base_title
else
  page_title + " | " + base_title
end

views/layouts./applicationにメソッドを記入

views/layouts/application.html.erb
<html>
#省略
  <head>
    <title><%= page_title(yield(:title)) %></title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
  </head>
#省略

<title>タグの中に、先ほど定義したpage_titleを記入することで、他のページにも柔軟に対応できるようになる。

③viewにタイトルを入れていく

ja.ymlにタイトルの翻訳を済ましている状態かどうか確認する。
例えば、ログインページのタイトルを入れたい時には、user_sessions.htmlファイル先頭にタイトルを設定。

user_sessions.html.rb
<% content_for(:title, t('.title')) %>

また投稿毎のタイトルを表示させたい場合は以下のようになる。

post.html.rb
<% content_for(:title, @post.title) %>

参考記事

[Rails] content_forでレイアウトの内容をviewから柔軟に変更する

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