Reputation: 120
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?
Upvotes: 8
Views: 4066
Reputation: 49743
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.
Upvotes: 19
Reputation: 80128
I've always found switching the requested format from HTML to Mobile to be against convention. It completely misuses the tool, so it's no wonder that you're running into problems trying to stay DRY.
Rather than switching the requested format, just check whether a given request is from a mobile device and set the layout based on that. Bing, bang, boom — done. No dicking around with something unrelated because someone else did, and you can get back to work.
I'd post code, but tybro0103 just beat me to the punch with a link to boot. Ooooh aaaaah!
Upvotes: 4