LoginSignup
1
0

More than 1 year has passed since last update.

content_forメソッドでタイトルを動的に出力する

Posted at

タイトルを動的に出力したいのでyieldメソッドとcontent_forメソッドをうまく利用する。
content_forメソッドを使うことでヘルパーメソッドが利用できるので、動的にタイトルを出力することができる。

まずは簡単にyieldメソッドとcontent_forメソッドの使い方を説明していく。

content_for

content_forは表示したいコンテンツを設定するのが役割。
content_forの公式

<%= content_for :コンテンツ名 do %> 
  コンテンツ
<% end %> 

具体例を用いて説明していく。

<%= content_for :title do %> 
  トップページ
<% end %> 

コンテンツ名を:titleとした。そしてコンテンツはトップページとする。
content_forでは表示したいコンテンツをdo~endで囲む。
ここでいうコンテンツはページのタイトルとして表示したい文字列を設定。

yield

yieldの公式

yield(:コンテンツ名)

今回は上記で設定したトップページという文字列を表示したいので、

yield(:title)

とする。このようにcontent_for(:コンテンツ名)で表示したいコンテンツを設定しておき、yield(:コンテンツ名)で設定したコンテンツを出力することができる。
これを利用してタイトルを動的に呼び出していく。

実践

今回はユーザー登録ページと、トップページで異なるタイトルを出力していく。

1、content_forメソッドで設定する。

top.html.erb
<%  content_for :title do %>
  page_title("トップ")
<% end %>
new.html.erb
<%  content_for :title do %>
  page_title("ユーザー登録")
<% end %>

今回は異なるタイトルを効率よく出力したいのでhelperメソッドを利用する。

2、ヘルパーメソッドを定義

application.helper.rb
module ApplicationHelper
  def page_title(title)
    title + "ページ"
  end
end

3、実際に出力する。

application.html.erb
<title><%= yield(:title) %></title>

以上で完成。

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