12
7

More than 3 years have passed since last update.

【Rails】TwitterのOGPを設定する

Last updated at Posted at 2020-05-29

Gemなしです。

TwitterのOGPを表示させるために必要なmetaタグについては以下の記事を参考にしました。
【2020年版】Twitterカードとは?使い方と設定方法まとめ

実装

app/helper/application_helper.rb
def full_title(page_title = '')
  base_title = 'MC BATTLE CHANNEL'
  if page_title.empty?
    base_title
  else
    "#{page_title} | #{base_title}"
  end
end

def full_url(path)
  domain = if Rails.env.development?
             'http://0.0.0.0:3000'
           else
             'https://mcbattle-ch.jp'
           end
  "#{domain}#{path}"
end
app/views/layouts/application.html.erb
<head>
  <!-- ogp -->
  <meta name="twitter:card" content="summary_large_image" />
  <meta name="twitter:site" content="@McBattleChannel" />
  <meta property="og:title" content="<%= full_title(yield(:title)) %>" />
  <meta property="og:url" content="<%= request.url %>" />
  <meta property="og:description"
    content="<%= content_for?(:description) ? yield(:description) : 'MCバトルの総合サイトです。' %>" />
  <meta property="og:image"
    content="<%= content_for?(:image_url) ? yield(:image_url) : full_url('/assets/other/ogp_default.png') %>" />
app/views/hoge/fuga.html.erb
<%= content_for(:title, "この個別ページのタイトル!") %>
<%= content_for(:description, "この個別ページの説明文!") %>
<%= content_for(:image_url, full_url("assets/mc/hoge.img")) %>

本番環境で表示されない場合

ステージング環境では表示されて、本番環境では表示されない場合、たぶんOGPのキャッシュが原因です。
以下の「OGPの表示を確認するツール」を使うと、表示確認と同時にキャッシュがクリアされます。
https://cards-dev.twitter.com/validator

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