Serving XHTML5 with Rails and HAML

After spending a few hours wrestling with the latest web-software I inflicted upon myself, it occured to me I’d best write instructions to my future self for reconfiguring this mess.

For reasons that are irrelevant to this article I need to generate XHTML, and would prefer to generate an HTML5 variant (yes, I know this doesn’t officially exist).

Rails appears to conflate the HTML and XHTML content-types. So we remove the existing HTML content-type and re-register those for HTML and XHTML.

# config/initializers/mime_types.rb
module Mime
    remove_const('HTML')
end

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

HAML may need to be told to generate XHTML. If you’re only concerned with generating a variant of XHTML hard coding this through an initializer is probably safe.

# config/initializers/haml.rb
Haml::Template.options[:format]    = :xhtml
Haml::Template.options[:mime_type] = "application/xhtml+xml"

Lastly, don’t forgot the namespacing for your root html element.

# app/views/layouts/application.xhtml.haml
!!! 5
%html{xmlns: "http://www.w3.org/1999/xhtml"}