LoginSignup
0
0

More than 1 year has passed since last update.

variantsによるテンプレートの切り替え

Posted at

variantsとは

条件によってテンプレートを切り替える機構としてvariantsという機能があります。
接続してきた端末によってPCとは別のテンプレートを表示したいという場合にこの機能が使えるようになります。

実際の流れになります。
controller内でrequest.variantに:tabletや:mobileなどの値を入力することで
viewテンプレートとして展開されるファイルを例えば、
index.html.erb → index.html+mobile.erb
このように"+"とrequest.variantの値のテンプレートが表示されるようになります。

具体的な動きを見ていきます。
① まずApplicationController内のbefore_actionでUserAgentを参照してrequest.variantの値を設定

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :detect_mobile_variant

  private

  def detect_mobile_variant
    request.variant = :mobile if request.user_agent =~ /iPhone/
  end
end

余談

UserAgentとは

UserAgentとはHTTOリクエストヘッダーに含まれるWEBノ使用環境に関する情報のことです。
ブラウザの種類、ブラウザのバージョン、端末のOSの種類などの情報が含まれています。

RailsにおけるUserAgentの取得方法

以下のようにUserAgentを取得することができる

requset.user_agent

UserAgent以外にも取得可能requestオブジェクト

request.url                 # リクエストで使われるURL全体
request.remote_ip           # クライアントのIPアドレス
request.query_string        # URLのクエリ文字

② mobile用のテンプレートの用意
今回はapp/views/books/show.html.erbをコピーし、
app/views/books/show.html+mobile.erbを作成する

app/views/books/show.html+mobile.erb
<h1>本の詳細情報(モバイルの見た目)</h1>

このようにすることでユーザーがmobileからアクセスしてきた際にmobile用のテンプレートが表示されます。

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