我正在使用移动fu gem来做一些用户代理检测,以便我可以根据客户端提供.html或.mobile扩展模板。

现在,这部分工作真的很好,但我不喜欢那个View文件夹变得有点杂乱,其中两倍于文件,即。

app/views/profiles/show.mobile.haml

app/views/profiles/show.html.haml

app/views/profiles/edit.mobile.haml

app/views/profiles/edit.html.haml

等等,等等

我想拥有的是:

app/views/profiles/html/show.html.haml

app/views/profiles/html/edit.html.haml

app/views/profiles/mobile/show.mobile.haml

app/views/profiles/mobile/edit.mobile.haml

并具有rails根据请求自动查看文件的正确文件夹/目录。 这可能做吗?

也许这是一个非常容易做的事情,请告诉我,如果这是出于框的行为..

谢谢

有帮助吗?

解决方案

Rails 4.1有一个名为 actionpack变型,检测用户 - 代理(如移动FU GEM)。

基本上,您可以在ApplicationController中添加如此:

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
.

让我们说你有一个Profilescontroller。现在你可以这样做:

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

返回您的问题:如果要在不同的文件夹/目录中查找文件,则可以执行以下操作:

format.html.phone { render 'mobile/index' }   # /app/views/mobile/index.html+phone.erb
.

还有一个良好的教程哪个显示如何使用它。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top