Dou*_*oug 7 ruby iphone layout before-filter 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
Run Code Online (Sandbox Code Playgroud)
这就是我最终做的事情:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2849 次 |
| 最近记录: |