0

Rails 3 uses a default DOCTYPE of HTML 5:

<!DOCTYPE html>

except a few lines below, it has

<meta name="csrf-param" content="authenticity_token"/>

I thought the HTML syntax is never to have the self-closing tags? (only XHTML/XML uses that, no?)

2 Answers 2

4

You can achieve the result you want if you are willing to override a built-in Rails method. If you do this, you run a slight risk of causing problems when upgrading to future versions of Rails that update this method's logic. Since both forms are valid according to the HTML5 spec, making the change below has very little payoff for HTML5. The only reasons I can think of to do this is if you are completely obsessive about your HTML code style or you are using an HTML 4 doctype. (The following csrf_meta_tag method is modified from Rails/ActionPack 3.0.7.)

module ActionView
  # = Action View CSRF Helper
  module Helpers
    module CsrfHelper
      # Returns a meta tag with the cross-site request forgery protection token
      # for forms to use. Place this in your head.
      def csrf_meta_tag
        if protect_against_forgery?
          %(<meta name="csrf-param" content="#{Rack::Utils.escape_html(request_forgery_protection_token)}">\n<meta name="csrf-token" content="#{Rack::Utils.escape_html(form_authenticity_token)}">).html_safe
        end
      end
    end
  end
end

I have also overridden the tag helper (changing the open parameter to default true instead of false) so that form helpers do not output self-closing tags.

module ActionView
  module Helpers
    module TagHelper
      def tag(name, options = nil, open = true, escape = true)
        "<#{name}#{tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe
      end
    end
  end
end

FWIW, I store extensions to existing classes in e.g. lib/extensions/action_view.rb; these extensions are loaded by config/initializers/extensions.rb which consists of:

Dir[File.join(Rails.root, 'lib', 'extensions', '*.rb')].each {|f| require f}
2

in HTML5, it is actually compliant to have self closing tags on void element such as meta, img, input, etc.

Ref: http://www.whatwg.org/specs/web-apps/current-work/#start

2
  • what about not having the self closing way but just to use it as <meta ...> ? If it is the same then why not use the short form? Mar 31, 2011 at 21:47
  • HTML5 is funky in the sense that it is compliant for both self closing and not self closing. This was made this way for the ease of migration from XML.
    – Mike Lewis
    Mar 31, 2011 at 21:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.