加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 04:21:50 所属栏目:百科 来源:网络整理
导读:我正在编写一个 Sinatra 应用程序,需要根据用户是使用iPhone还是常规浏览器呈现不同的布局.我可以使用 Rack-Mobile-Detect检测浏览器类型,但我不确定告诉Sinatra使用哪种布局的最佳方式. 此外,我有一种感觉,我如何选择这样做也可能会破坏页面缓存.真的吗?
我正在编写一个 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读