secret
Created

  • Download Gist
driver.rb
Ruby
1 2 3 4 5 6
require_relative 'escaped'
 
template = File.read('input.haml')
haml_engine = Haml::Engine.new(template)
output = haml_engine.render
puts output
escaped.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
require 'haml'
 
module SafeMarkdown
include Haml::Filters::Markdown
include Haml::Filters::Base
 
#this bit copied from Haml::Filters::Markdown
lazy_require 'rdiscount', 'peg_markdown', 'maruku', 'bluecloth'
 
# This bit copied from Haml::Filters::Base with only the addition
# of the second parameter to the call to unescape_interpolation added
def compile(compiler, text)
resolve_lazy_requires
filter = self
compiler.instance_eval do
if contains_interpolation?(text)
return if options[:suppress_eval]
 
text = unescape_interpolation(text, true).gsub(/(\\+)n/) do |s|
escapes = $1.size
next s if escapes % 2 == 0
("\\" * (escapes - 1)) + "\n"
end
# We need to add a newline at the beginning to get the
# filter lines to line up (since the Haml filter contains
# a line that doesn't show up in the source, namely the
# filter name). Then we need to escape the trailing
# newline so that the whole filter block doesn't take up
# too many.
text = "\n" + text.sub(/\n"\Z/, "\\n\"")
push_script <<RUBY.rstrip, :escape_html => false
find_and_preserve(#{filter.inspect}.render_with_options(#{text}, _hamlout.options))
RUBY
return
end
 
rendered = Haml::Helpers::find_and_preserve(filter.render_with_options(text, compiler.options), compiler.options[:preserve])
 
if !options[:ugly]
push_text(rendered.rstrip.gsub("\n", "\n#{' ' * @output_tabs}"))
else
push_text(rendered.rstrip)
end
end
end
end
input.haml
Haml
1 2 3
:safemarkdown
Hello #{"<a href=\"evil\">My name</a>"}.
<strong>But this remains</strong>.
out.html
HTML
1 2
<p>Hello &lt;a href=&quot;evil&quot;&gt;My name&lt;/a&gt;.
<strong>But this remains</strong>.</p>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.