In sinatras using erubis, the default escape_html is true. sometimes hava unescape

In Sinatra, using erubis, the default escape_html

is true

.

But sometimes I want to unescape because I don't want to add too much escape_html. Don't repeat yourself. :)

helpers:

def raw(string)
  CGI::unescape_html(string)
end

      

views:

<div class="body">
  <%= raw "<h1>Thanks for help...</h1>" %>
</div>

      

does not work.

+3


source to share


3 answers


Not sure which version of Erubis you are using, but it looks like it has a special tag for this particular case: two is the same. So the line from your example might look like:

<%== "<h1>Thanks for help...</h1>" %>

      

CGI::unescape

No call is required because the string is not originally escaped. All you need to do is prevent escaping, not cancel it.



But if your erubs don't understand <%==

, or if you are using ERB and not Erubis, then sorry, I don't know of any other solution other than what you said: disable html escape for the entire file and use h

wherever you need to elude.

FYI, Rails also has special helpers for this raw

and String#html_safe

, but as I see they are part of ActiveSupport and not available in Sinatra.

+3


source


Just add some tips. Erubis has the ability to avoid (mislead) expression. Erubis :: The Eruby class acts as follows:

<%= expr %> - not escaped.
<%== expr %> - escaped.
<%=== expr %> - out to $stderr.
<%==== expr %> - ignored.

      



Source

+4


source


You can accomplish what you want:

Web.rb:

require 'sinatra'
require 'erubis'
set :erb, :escape_html => true

get '/hi' do
  @model = Hash.new()
  @model[:person] = "<b>World</b>"
  erb :hello
end

      

Layout.erb:

<!DOCTYPE html>
<html>
<head>
  <title><%= @title %></title>
</head>
<body>
  <%== yield %>
</body>
</html>

      

Hello.erb:

<div>
  <p>Hello, <%= @model[:person] %>!</p>
  <p>Hello, <%== @model[:person] %>!</p>
</div>

      

0


source







All Articles