14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RailsでUserAgentに応じてlayoutを切り替える

Last updated at Posted at 2016-01-29

UserAgentに応じてlayoutをかえる方法の備忘です。

UserAgentの判定はrack-user_agentというGemを使います。
UserAgentをパースしてrequestの中にosや端末の種類などをいれてくれる便利なGemです。

レイアウト切り替え

ポイントはlayout関数の引数を関数にしている点です。
関数にすることで動的に切り替えが可能です。

ソース

class ApplicationController < ActionController::Base
  layout :select_layout
  #スマートフォンのときは縮小版レイアウトを表示
  def select_layout
    if request.from_pc? || request.from_android_tablet? || request.from_ipad?
      "sp_layout"
    else
      "application"
    end
  end
14
14
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?