我正在我们普通的 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 部分就可以很好地与移动设备一起使用。我可以选择使用移动部分与使用
“self.formats = [:mobile, :html] if @mobile_site”位于 index.html.erb 的开头。但在所有模板的开头写这个感觉很愚蠢。
所以问题是:
- self.formats 在视图中出现在哪里(最初设置它的是什么)以及如何设置它始终在移动网站内 [:mobile, :html] ?为什么它与我在控制器 before_filter 中设置的不一样?我可以在控制器中以某种方式设置它吗?
(小奖励问题)