ruby – 在Sinatra中,提供iPhone布局与正常布局的最佳方式是什么?

前端之家收集整理的这篇文章主要介绍了ruby – 在Sinatra中,提供iPhone布局与正常布局的最佳方式是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在编写一个 Sinatra应用程序,需要根据用户是使用iPhone还是常规浏览器呈现不同的布局.我可以使用 Rack-Mobile-Detect检测浏览器类型,但我不确定告诉Sinatra使用哪种布局的最佳方式.

此外,我有一种感觉,我如何选择这样做也可能会破坏页面缓存.真的吗?

示例代码

require 'sinatra/base'
require 'haml'
require 'rack/mobile-detect'

class Orca < Sinatra::Base

  use Rack::MobileDetect

  helpers do
    def choose_layout
      if request.env['X_MOBILE_DEVICE'] == :iPhone
        # use iPhone layout
      else
        # use normal layout
      end
    end
  end

  before do
    # should I use a before filter?
    choose_layout()  
  end

  get '/' do
    haml :home # with proper layout
  end

end #Class Orca

解决方法

这就是我最终做的事情:
require 'sinatra/base'
require 'haml'
require 'rack/mobile-detect'

class Orca < Sinatra::Base

  use Rack::MobileDetect

  # HAML template options
  # Use HTML5 doctype
  set :haml,{:format => :html5 }

  helpers do

    def get_layout
      # For AJAX (XMLHttpRequest) requests,don't use a layout
      if request.xhr? then 
        @layout = false
        exit
      end

      # For non-AJAX (XMLHttpRequest) requests,choose correct layout
      # For each mobile device,you will need a layout_<device>.haml file
      # in the Views directory
      @layout = case request.env['X_MOBILE_DEVICE']
                when /iPhone|iPod/ then :layout_iphone

              # when "Android" then :layout_android

                else true # use default Sinatra layout
                end
    end

  end # helpers

  before do
    get_layout() 
  end # before filter

  get '/' do
    # Will use iPhone layout for iPhone|iPod,# Sinatra default layout for desktop browsers
    haml :home,:layout => @layout
  end

end # Class
原文链接:https://www.f2er.com/ruby/268611.html

猜你在找的Ruby相关文章