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

前端 未结 5 520
说谎
说谎 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:15

    You can register new format for the whole application in your mime type initializers:

     Mime::Type.register_alias "text/html", :mobile
    

    Now you can do something like this in your templates to specify format priority(see How do I render a partial of a different format in Rails?):

    <% self.formats = [:mobile, :html] %>
    

    In this case if there is mobile template it will be used for rendering with fallback to ordinary html template. Now you should only determine if user is browsing via mobile browser and conditionally execute this code. Or you can just assign formats value in ApplicationController filter so correct template will be chosen automaticaly.

    UPDATE:

    It seems like by this time there is no "legal" way to solve this problem using Rails. Here is unclosed issue in the rails repository. There you can find patch that can solve your problem, but it uses private Rails API, so it can be unstable.

    Also you can try implement your own view resolver that possibly can solve the problem: http://jkfill.com/2011/03/11/implementing-a-rails-3-view-resolver/

提交回复
热议问题