Using an alternative Rails layout, but the same look on mobile devices

I used the same tactics in railscast for mobile to provide an alternative layout for my site in a mobile browser.

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

The problem is that I don’t want to create completely new views, it’s just the layout I want to change. If I do not create the so-called view, the mobile layout will never be used. Since-I can only change both or neither on mobile devices.

What am I missing here? How can I get rails to replace only the layout when I have a mobile user?

+8
ruby-on-rails layout mobile views
source share
2 answers

Assuming you added the mobile_device? method mobile_device? from railscasts, just 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 display the same view, don't worry about setting request.format.

+18
source share

I always found the conversion of the requested format from HTML to mobile to be against the convention. He completely abuses the tool, so it is not surprising that you are having trouble trying to stay dry.

Instead of switching the requested format, just check if the given request is a mobile device and configure it based on this. Bing, bang, boom - done. Do not deceive anything with something unrelated, because someone else has done it, and you can return to work.

I would post the code, but tybro0103 just beat me before the hit with the download link. Ooooh aaaaah!

+4
source share

All Articles