3

我试图让我的 Rails 应用程序以正确的内容类型为 application/xhtml+xml 提供 XHTML 内容。理想情况下,内容协商使 IE 用户也有机会使用该网站。

鉴于 Rails 生成的所有 HTML 都标记为 XHTML 1.0 Transitional,我有点惊讶于没有明显的选项可以让 Rails 将标记作为 XHTML。我发现了这个http://blog.codahale.com/2006/05/23/rails-plugin-xhtml_content_type/,但它似乎适用于 1.1.2,我无法让它在 2.3.8 下正常工作。

我在这里错过了什么吗?

4

3 回答 3

2

好的,我现在有一些可以工作的东西。感谢@danivovich 让我在正确的地方开始。我要做的第一件事是整理 mime_types.rb 中的 Mime 类型,这样 HTML 就不会被 XHTML 别名:

module Mime
  remove_const('HTML') # remove this so that we can re-register the types
end

Mime::Type.register "text/html", :html
Mime::Type.register "application/xhtml+xml", :xhtml

我刚刚将它添加到我的应用程序控制器中:

  before_filter :negotiate_xhtml
  after_filter :set_content_type

  def negotiate_xhtml
    @serving_polyglot = false
    if params[:format].nil? or request.format == :html
      @serving_polyglot = ((not request.accepts.include? :xhtml) or params[:format] == 'html')
      request.format = :xhtml
    end
  end

  def set_content_type
    if @serving_polyglot
      response.content_type = 'text/html'
    end
  end    

This makes sure that XHTML is always servered as such, unless the client doesn't accept it, or HTML has been explicitly requested. HTML is always just XHTML served as a polyglot. The @serving_polyglot variable is available in the views where any switching is needed.

This is working for me under Chrome, Safari, Firefox, Opera and IE[6-8].

于 2010-07-06T21:52:05.993 回答
1

您可以在任何控制器功能或使用后过滤器中强制使用内容类型。这些方法中的任何一种都可以通过以下方式设置内容类型:

response.content_type = "application/xhtml+xml"
于 2010-07-04T19:42:27.037 回答
0

将此添加到您的application_controller.rb

 def correct_safari_and_ie_accept_headers
    ajax_request_types = [ 'text/javascript', 'application/json', 'text/xml']
    request.accepts.sort!{ |x, y| ajax_request_types.include?(y.to_s) ? 1 : -1 } if request.xhr?
 end

这更正了 safari 和 ie 接受标头,使其默认为text/xml而不是text/html. 这个对我有用。在 IE 和 Safari 上都经过测试。其他浏览器默认为text/xml反正。

编辑:我已将我的 DOCTYPE 设置为<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">而不是 XHTML 过渡。

于 2010-07-05T05:00:50.860 回答