Changing view formats in rails 3.1 (delivering mobile html formats, fallback on normal html)

前端 未结 5 545
说谎
说谎 2021-01-14 18:36

I\'m creating a mobile site next to our normal html site. Using rails 3.1. Mobile site is accessed in subdomain m.site.com.

I have defined mobile format (Mime::Type.

5条回答
  •  一向
    一向 (楼主)
    2021-01-14 19:11

    I think I've found the best way to do this. I was attempting the same thing that you were, but then I remembered that in rails 3.1 introduced template inheritance, which is exactly what we need for something like this to work. I really can't take much credit for this implementation as its all laid out there in that railscasts link by Ryan Bates.

    So this is basically how it goes.

    Create a subdirectory in app/views. I labeled mine mobile.

    Nest all view templates you want to override in the same structure format that they would be in the views directory. views/posts/index.html.erb -> views/mobile/posts/index.html.erb

    Create a before_filter in your Application_Controller and do something to this effect.

     before_filter :prep_mobile
     def is_mobile?
       request.user_agent =~ /Mobile|webOS|iPhone/
     end 
     def prep_mobile
       prepend_view_path "app/views/mobile" if is_mobile?
     end
    

    Once thats done, your files will default to the mobile views if they are on a mobile device and fallback to the regular templates if a mobile one is not present.

提交回复
热议问题