【发布时间】:2012-02-10 09:43:39
【问题描述】:
我正在我们的普通 html 网站旁边创建一个移动网站。使用导轨 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 我有自动选择 index.html.erb 或 index.mobile.erb 的索引操作。不需要在移动视图顶部进行额外编码。成功。
但我有很多其他视图,其中相同的模板可用于在移动布局中提供服务,但只需稍作改动。
例如在 MessagesController 中,相同的视图几乎适用于移动设备
In index.html.erb
Normal user info, common for mobile and html
<%= render(:partial => 'messages') %>
渲染messages.html.erb,不需要messages.mobile.erb。移动视图可以用 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 使用 "self.formats = [:mobile, :html] if @mobile_site" 在 index.html.erb 的开头。但是在所有模板的开头写这个感觉很愚蠢。
所以问题是:
- self.formats 在视图中的位置(最初设置它的原因)以及如何设置它始终是移动网站内的 [:mobile, :html]?为什么它和我在控制器 before_filter 中设置的不一样?我可以在控制器中以某种方式进行设置吗?
(小问题)
这种方法有问题吗?使用几乎相同的 html 视图,在某些特定情况下使用 mobile.erb 视图。为什么默认情况下这在 Rails 中不起作用?
如果发现 :mobile 视图可以退回到正常的 html 视图,是否还有其他方法可以选择呈现?甚至跨越部分,以便 html.erb-view 尝试使用 _partial.mobile.erb 部分。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3.1