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

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

    Rails 4.1 includes a pretty neat feature:

    Variants

    Allows you to have different templates and action responses for the same mime type (say, HTML). This is a magic bullet for any Rails app that's serving mobile clients. You can now have individual templates for the desktop, tablet, and phone views while sharing all the same controller logic.

    Now you can do something like this:

    class PostController < ApplicationController
      def show
        @post = Post.find(params[:id])
    
        respond_to do |format|
          format.json
          format.html               # /app/views/posts/show.html.erb
          format.html.phone         # /app/views/posts/show.html+phone.erb
          format.html.tablet do
            @show_edit_link = false
          end
        end
      end
    end
    

    You simply need to set the variant depending on your needs, for example within a before_filter:

    class ApplicationController < ActionController::Base
      before_action :detect_device_variant
    
      private
    
        def detect_device_variant
          case request.user_agent
          when /iPad/i
            request.variant = :tablet
          when /iPhone/i
            request.variant = :phone
          end
        end
    end
    

    What's new in Rails 4.1

提交回复
热议问题