Skip to content

Instantly share code, notes, and snippets.

@cheald
Created November 23, 2012 05:06
Show Gist options
  • Save cheald/4134080 to your computer and use it in GitHub Desktop.
Save cheald/4134080 to your computer and use it in GitHub Desktop.
# Renders the given content or block in a CDATA section if necessary. If CDATA is not necessary, the raw data is returend.
# @param data [String] The data to render. Nil if passing a block.
# @yield Template fragment to encode as CDATA if necessary.
def cdata(data = nil)
data = data.dup if data.present? and data.frozen?
if data
data.strip!
data.gsub!(/\]\]>/, "]]>")
if match = data.match(/([<>&]|[^\x20-\x7f])/)
data = "\n%s" % data if data.match(/\n/)
data.gsub!(/[^\x20-\x7f]/) {|m| "&##{m.ord};" }
"<![CDATA[#{ data }]]>".html_safe
else
data.html_safe
end
elsif block_given?
# Passes the given block, if one was given, without instantiating a block for every cdata call.
cdata capture_haml(&Proc.new)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment