Unescaping HAML in an Attribute Hash

谁都会走 提交于 2019-12-05 05:54:12

There isn’t (currently) any way to turn off escaping for an individual attribute in Haml outside of Rails, it’s all or nothing using the :escape_attrs option. Depending on what you want, it might be worth looking at the :once option.

When Haml is used in Rails, it replaces the html escaping methods with some that respect the html_safe value that ActiveSupport adds (see lib/haml/helpers/xss_mods.rb).

It is possible to use these methods outside of Rails if you want. You will need to add html_safe and html_safe? methods to the String class in order for this to work (be careful here, this example is only a “poor man’s” version of the full XSS protection that Rails provides, it won’t really protect you from much but it will allow selective escaping of attributes).

Add the following somewhere after requiring Haml (it might be best in its own file that gets required):

class String
  def html_safe?
    defined?(@html_safe) && @html_safe
  end

  def html_safe
    @html_safe = true
    self
  end
end

require 'haml/helpers/xss_mods'

module Haml::Helpers
  include Haml::Helpers::XssMods
end

Now you can use html_safe on your strings, and Haml won’t escape them:

.myclass{ "extraattr" => "UNESCAPED <>& CONTENT".html_safe,
          "otherextraattr" => "ESCAPED <>& CONTENT"}
  Content...

Output:

<div class='myclass' extraattr='UNESCAPED <>& CONTENT' otherextraattr='ESCAPED &lt;&gt;&amp; CONTENT'>
  Content...
</div>

Have you tried using a \ to escape the characters.

{ :myattr => '\<\>\&' }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!