开发者

In Rails 3, the default DOCTYPE is HTML 5, but it uses <meta name="csrf-param" content="authenticity_token"/>?

开发者 https://www.devze.com 2023-02-20 23:18 出处:网络
Rails 3 uses a defa开发者_运维知识库ult DOCTYPE of HTML 5: <!DOCTYPE html> except a few lines below, it has

Rails 3 uses a defa开发者_运维知识库ult 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?)


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}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号