Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an alternate Rails layout, but same view, on mobile devices

I've been using the same tactics in the Mobile Devices railscast to provide an alternate layout for my site in a mobile browser.

When a mobile browser is detected, the request.format is set to :mobile, which I've defined as a mime type. I have created a new layout for mobile devices. If I provide a mobile view (e.g. show.mobile.haml), both the mobile view and layout are used on mobile devices, and everything works great.

The problem is, I don't want to create entirely new views, it's just the layout I want to change. If I don't create an appropriately named view, the mobile layout is never used. So as-is I can only manage to change both or neither on mobile devices.

What am I missing here? How can I get rails to swap out just the layout when I've got a mobile user?

like image 652
Kelly Avatar asked Aug 13 '11 02:08

Kelly


1 Answers

Assuming you have added the mobile_device? method from railscasts then simply add the following to application_controller.rb:

  layout :which_layout
  def which_layout
    mobile_device? ? 'mobile' : 'application'
  end

Be sure to create the mobile.html.erb file in app/views/layouts

Since you want to render the same view, don't worry about setting the request.format.

like image 83
tybro0103 Avatar answered Oct 26 '22 17:10

tybro0103