2

我正在尝试利用 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 完成此任务?

4

2 回答 2

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
于 2014-05-03T21:34:08.450 回答
0

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

于 2018-06-20T21:35:39.053 回答