我正在我们的普通 html 站点旁边创建一个移动站点。使用 rails 3.1。移动站点在子域 m.site.com 中访问。
我已经定义了移动格式(Mime::Type.register_alias "text/html", :mobile)。
在 ApplicationController 中,我有“before_filter :mobile_site_before_filter”可以识别移动站点并根据它设置格式。
def mobile_site_before_filter
if request.subdomains.first == 'm'
original_format = request.format
request.format = :mobile
@mobile_site = true
request.formats.push(original_format)
end
end
在布局中,我有“main.html.erb”和“main.mobile.erb”。因此,对于移动站点,使用移动布局。
现在它可以正常工作了。
在 UserController 我有索引 Action ,它自动选择 index.html.erb 或 index.mobile.erb 。无需在移动 View 顶部进行额外编码。成功。
但是我还有很多其他 View ,可以使用相同的模板在移动布局内部提供服务,但只需稍作改动。
例如。在 MessagesController 中,相同的 View 几乎适用于移动设备
In index.html.erb
Normal user info, common for mobile and html
<%= render(:partial => 'messages') %>
渲染messages.html.erb,不需要messages.mobile.erb。移动 View 可以用css完成
<%# By default self.formats = [:html] because this is .html.erb partial, even in mobile site %>
<%= self.formats = [:mobile, :html] if @mobile_site # How to get rid of this? %>
<%= render(:partial => 'vote_form') %>
<!-- rest of page ... -->
现在我想根据网站呈现vote_form.[mobile|html].erb...
现在,如果我可以在vote_form.html.erb 或vote_form.mobile.erb 之间进行选择,那么index.html.erb 部分就可以与移动设备一起使用。我可以choose to use mobile partial使用
index.html.erb 开头的“self.formats = [:mobile, :html] if @mobile_site”。但是在所有模板的开头写这个感觉很愚蠢。
所以问题是:
(小奖励问题)
最佳答案
我想我已经找到了最好的方法来做到这一点。我正在尝试与您相同的事情,但后来我记得在 rails 3.1 中引入了 template inheritance ,这正是我们需要的东西才能工作。我真的不能对这个实现给予太多的信任,因为它的所有内容都在 Ryan Bates 的 railscasts 链接中列出。
所以基本上就是这样。
在app/views
中创建子目录.我标记了我的 mobile
.
嵌套所有要覆盖的 View 模板,其结构格式与 View 目录中的结构格式相同。 views/posts/index.html.erb -> views/mobile/posts/index.html.erb
创建一个 before_filter
在您的 Application_Controller
并为此做点什么。
before_filter :prep_mobile
def is_mobile?
request.user_agent =~ /Mobile|webOS|iPhone/
end
def prep_mobile
prepend_view_path "app/views/mobile" if is_mobile?
end
完成后,如果您的文件在移动设备上,您的文件将默认为移动 View ,如果移动设备不存在,则回退到常规模板。
关于ruby-on-rails - 在 rails 3.1 中更改 View 格式(提供移动 html 格式,回退到普通 html),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8863257/