加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在rails 3.1中更改视图格式(提供移动html格式,

发布时间:2020-12-17 01:49:26 所属栏目:百科 来源:网络整理
导读:我正在我们正常的html网站旁边创建一个移动网站.使用rails 3.1.移动站点在子域m.site.com中访问. 我已经定义了移动格式(Mime :: Type.register_alias“text / html”,:mobile). 在ApplicationController中,我有“before_filter:mobile_site_before_filter
我正在我们正常的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中,我有索引操作,它自动选择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 partial可以用于移动设备.我可以使用choose to use mobile partial
在index.html.erb的开头,“self.formats = [:mobile,:html] if @mobile_site”.但是在所有模板的开头写这个都感觉很愚蠢.

所以问题是:

> self.formats在视图中的位置(最初设置的是什么)以及如何在移动站点内设置它始终是[:mobile,:html]?为什么它与我在控制器before_filter中设置的不一样?我可以在控制器中以某种方式设置它吗?

(小额奖金问题)

>这种方法有什么问题吗?使用大多数相同的html视图,在某些特定情况下使用mobile.erb视图.为什么默认情况下这不适用于rails?
>是否有其他方法可以选择渲染:如果找到移动视图,则回退到正常的html视图?甚至跨越部分,以便html.erb-view尝试使用_partial.mobile.erb部分.

解决方法

您可以在mime类型初始值设定项中注册整个应用程序的新格式:

Mime::Type.register_alias "text/html",:mobile

现在,您可以在模板中执行类似的操作以指定格式优先级(请参阅How do I render a partial of a different format in Rails?):

<% self.formats = [:mobile,:html] %>

在这种情况下,如果有移动模板,它将用于渲染回退到普通的html模板.现在,您应该只确定用户是否通过移动浏览器进行浏览并有条件地执行此代码.或者您可以在ApplicationController过滤器中指定格式值,以便自动选择正确的模板.

更新:

好像到了这个时候,没有“合法”的方法来使用Rails解决这个问题.这是rails库中的unclosed issue.在那里你可以找到可以解决你的问题的补丁,但它使用私有的Rails API,所以它可能不稳定.

您也可以尝试实现您自己的可能解决问题的视图解析器:http://jkfill.com/2011/03/11/implementing-a-rails-3-view-resolver/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读