如何为 Rails 应用程序制作 pc 和移动布局?
How to make pc and mobile layout for a Rails application?
我已经按照这个教程做了:
http://railscasts.com/episodes/199-mobile-devices?view=asciicast
现在我有 app/views/layouts/pc.html.erb
和 app/views/layouts/mobile.html.erb
。
我试图将这些代码添加到 application_controller.rb:
private
def mobile_device?
if session[:mobile_param]
session[:mobile_param] == "1"
else
request.user_agent =~ /Mobile/
end
end
def prepare_for_mobile
session[:mobile_param] = params[:mobile] if params[:mobile]
request.format = :mobile if mobile_device?
end
protected
def layout_by_device
if mobile_device?
render layout: "mobile"
else
render layout: "pc"
end
end
在我的 products_controller.rb 中:
before_action :layout_by_device
def show
respond_to do |format|
format.html
format.mobile
end
end
但是我只能看到我的移动布局的内容,我看不到产品页面的内容:yield
。
如果我删除 before_action :layout_by_device
并在我的 products_controller.rb 中使用 render layout: 'mobile'
,我可以看到产品页面的内容,但看不到移动布局的内容。
也许这是关于 Rails' respond_to
和 render
。怎么办?
并不是要阻止您遵循本教程,但如果您的目标是调整您的应用程序以适应小屏幕及其限制,那么保持单独 layouts/views 的方法就相当过时了。你的时间最好花在学习响应式网页设计上,这是让页面元素 grow/shrink 具有可用屏幕尺寸的概念。
我找到了正确的解决方案:
2.3 Action Pack 变体 是我想要的。
request.variant
我已经按照这个教程做了:
http://railscasts.com/episodes/199-mobile-devices?view=asciicast
现在我有 app/views/layouts/pc.html.erb
和 app/views/layouts/mobile.html.erb
。
我试图将这些代码添加到 application_controller.rb:
private
def mobile_device?
if session[:mobile_param]
session[:mobile_param] == "1"
else
request.user_agent =~ /Mobile/
end
end
def prepare_for_mobile
session[:mobile_param] = params[:mobile] if params[:mobile]
request.format = :mobile if mobile_device?
end
protected
def layout_by_device
if mobile_device?
render layout: "mobile"
else
render layout: "pc"
end
end
在我的 products_controller.rb 中:
before_action :layout_by_device
def show
respond_to do |format|
format.html
format.mobile
end
end
但是我只能看到我的移动布局的内容,我看不到产品页面的内容:yield
。
如果我删除 before_action :layout_by_device
并在我的 products_controller.rb 中使用 render layout: 'mobile'
,我可以看到产品页面的内容,但看不到移动布局的内容。
也许这是关于 Rails' respond_to
和 render
。怎么办?
并不是要阻止您遵循本教程,但如果您的目标是调整您的应用程序以适应小屏幕及其限制,那么保持单独 layouts/views 的方法就相当过时了。你的时间最好花在学习响应式网页设计上,这是让页面元素 grow/shrink 具有可用屏幕尺寸的概念。
我找到了正确的解决方案:
2.3 Action Pack 变体 是我想要的。
request.variant