LoginSignup
1
1

More than 5 years have passed since last update.

metaタグを動的に作成する

Last updated at Posted at 2016-07-23

動的ページのメタタグを作成したい

HTMLの<head>~</head>のメタタグを商品ページ等動的に作られたページに
固有のタグを入れたい。
今回入れるのは keywordsとdescription

まず共通で作っていたヘッダの定義を見てみると、

_head.haml
~~~前略~~~
!= meta_data_tags
~~~後略~~~

となっており、ここでmetaタグを作っている見たい

実装してみる

まずはhelperにデフォルトのmetaタグを作成する

helper.rb
~~~前略~~~
  def meta_data
    if (defined? my_meta_data)
      my_meta_data
    else
      ({
          keywords: "default keyword",
          description: "default Description",
      })
    end
  end

続いて動的ページを作成するControllerで読み込んだページ毎のmetaを上書きする。

xxx_controller.rb
  helper_method :my_meta_data

  private
    def search_items(item_id)
      @item = Items.find(item_id)
    end
    def my_meta_data
      if @item.present?
        ({
          keywords: @item.keywords,
          description: @item.description,
        })
      else
        ({
            keywords: "",
            description: "",
        })
      end
    end

テーブルには事前にkeywordsとdescriptionを作成し、
商品毎のkeywordとDescriptionを登録すれば、
新しい商品を追加するときもRecordを追加するだけで対応可能。

my_meta_dataが作られていなければ、defaultのkeywordとDescriptionが設定される。

生成されたHTMLはこんな感じ

・動的に取得しないページ

test.html
<head>
  <meta name="keywords" content="default keyword">
  <meta name="description" content="default Description">

</head>

・itemから取得したページ

test.html
<head>
  <meta name="keywords" content="アイテムのkeyword">
  <meta name="description" content="アイテムのDescription">

</head>
1
1
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
1