Serving XHTML as an Application / xhtml + xml with Ruby on Rails

I am trying to get a Rails application to properly serve XHTML content with the correct application content type / xhtml + xml. Ideally, with content negotiation, IE users should be able to use the site too.

Given that all the HTML generated by Rails is tagged in XHTML 1.0 Transitional, I am a little surprised that there is no obvious way to markup Rails as XHTML. I found this http://blog.codahale.com/2006/05/23/rails-plugin-xhtml_content_type/ , but it seems to be for 1.1.2, and I cannot get it to work properly in section 2.3.8.

Did I miss something?

+3
source share
3 answers

Ok, I have something that works now. Thanks @danivovich for starting me in the right place. The first thing I needed to do was sort the Mime types in mime_types.rb so that HTML was not an alias with 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

I just added this to my application 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    

This ensures that XHTML is always the server as such if the client does not accept it or if HTML is explicitly requested. HTML is always just XHTML served as a polyglot. The @serving_polyglot variable is available in views where any switching is required.

This works for me in Chrome, Safari, Firefox, Opera, and IE [6-8].

+2
source

after. :

response.content_type = "application/xhtml+xml"
+1

Add this to your 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

It fixes safari etc. accepts headers so that by default it is text/xmlinstead text/html. It works for me. Tested on both IE and Safari. In other browsers it is by default used text/xml.

EDIT . I installed DOCTYPE for <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">, and not XHTML Transitional.

0
source

Source: https://habr.com/ru/post/1753066/


All Articles