我正在尝试让我的 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 下正常工作。
我是不是漏掉了什么?
最佳答案
好的,我现在有一些东西可以用了。感谢@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
我刚刚将其添加到我的应用程序 Controller 中:
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
这可以确保 XHTML 始终按原样提供服务,除非客户端不接受它,或者已明确请求 HTML。 HTML 始终只是充当多语言的 XHTML。 @serving_polyglot 变量在需要任何切换的 View 中可用。
这在 Chrome、Safari、Firefox、Opera 和 IE 下对我有用[6-8]。
关于ruby-on-rails - 使用 Ruby on Rails 将 XHTML 作为 application/xhtml+xml 提供服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3175824/