如何配置Rails 4.1 Variants使用的默认布局?

时间:2014-05-03 21:25:39

标签: ruby-on-rails layout render variants

我试图利用Rails Variants为手机使用不同的布局,为平板电脑+台式机使用不同的布局(默认布局)。

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  before_action :detect_device_format

  private

    def detect_device_format
      case request.user_agent
      when /iPad/i
        request.variant = :tablet
      when /iPhone/i
        request.variant = :phone
      when /Android/i && /mobile/i
        request.variant = :phone
      when /Android/i
        request.variant = :tablet
      when /Windows Phone/i
        request.variant = :phone
      end
    end
end

class HomeController < ApplicationController
  def index
    respond_to do |format|
      format.json
      format.html          # /app/views/home/index.html.erb
      format.html.phone    # /app/views/home/index.html+phone.erb
      format.html.tablet   # /app/views/home/index.html+tablet.erb
    end
  end
end

现在,我知道我可以使用像format.html.phone { render layout: 'application-mobile' }这样的东西,但我不想每次都这样做。

我希望保持干爽并创建默认的手机布局。

如何使用Rails 4.1实现此目的?

2 个答案:

答案 0 :(得分:3)

这是通用,您可以根据需要进行调整。

应用程序控制器:

def set_layout
    case request.user_agent
    when /iPad/i, /Android/i
        "tablet"
    when /iPhone/i, /Android/i && /mobile/i, /Windows Phone/i
        "phone"
    else
        "application"
    end
end

在任何控制器中:

layout :set_layout

编辑:使用此解决方案,您不必使用此功能:

format.html          # /app/views/home/index.html.erb
format.html.phone    # /app/views/home/index.html+phone.erb
format.html.tablet   # /app/views/home/index.html+tablet.erb

一切都会响应

format.html

答案 1 :(得分:0)

只需命名您的布局{layout}.html+{variant}.erb。例如,如果您的变体设置为phone,则Rails将寻找application.html+phone.erb