Automatic html escaping with Sinatra and Erubis

Language: Ruby

# Requires Sinatra >= 1.0 and Tilt >= 0.9
# (fyi Tilt 0.8 is bundled with Sinatra 1.0, so you'll need to upgrade 
# to the latest gem version)
#
# Tilt 0.9 adds an :escape_html option for Erubis, which allows you
# to leverage Erubis' auto-escape functionality, so that anything inside 
# <%= %> blocks will be html-escaped by default. 
#
# To skip escaping, use a <%== %> block.
require 'rubygems'
gem "sinatra", ">= 1.0"
gem "tilt", ">= 0.9"
require 'sinatra'
require 'erubis'

# Globally set erubis to render with auto-escaping of html
set :erubis, :escape_html => true

get '/' do
  erubis :index
end

helpers do
  # Convenience method for manually escaping html
  def h(text)
    Rack::Utils.escape_html(text)
  end
  
  def link_to(text, href)
    %(<a href="#{href}">#{h(text)}</a>)
  end
end

__END__

@@ index
<p><%= "This string <b>will</b> be html escaped."%></p>
<p><%== "This string <b>will not</b> be html escaped."%></p>
<p><%== link_to "This link tag inner text <b>will</b> be escaped manually in our link_to helper, but the surrounding tag will not", "#" %></p>

@@ layout
<!DOCTYPE HTML>
<head><title>Erubis escaping test</title></head>
<body><%== yield %></body>
Reveal More
Added about 6 years ago by Gbuesing gbuesing