Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinatra & HAML: auto-escape/convert unsafe HTML characters for a whole template?

I've got a little sinatra app I'm using to run a basic website. The content for said site is being provided by a client, and most of it is coming out of PDFs. Since I'd rather not have to manually replace all the < with &lt;, and the & with &amp;, is there a way to configure HAML/Sinatra to do it for me automatically?

Basically, I have some blocks that look like this:

%p
  large block of text here...
  multi-line so I can see it in my IDE...
  more lines here...

I'd like to just find some config option that tells HAML to go through all of the content and replace unsafe characters with their HTML entity counterparts.

I tried using the HTMLEntities gem, but this site has a lot of multi-line paragraphs, and I couldn't seem to get it to work. By that I mean that I would do something like this in my server.rb file:

def "/some_url"
  @encoder = HTMLEntities.new
  haml :some_template
end

And in my template:

%p
  = @encoder.encode("Really long multiline string...
    some more lines here...
    and more lines...")

And it would spit out an error about missing a closing ).

like image 229
Kevin Whitaker Avatar asked Feb 17 '23 05:02

Kevin Whitaker


1 Answers

You could use the :escaped filter:

%p
  :escaped
    A block of text here that might
    contain & and <.

output:

<p>
  A block of text here that might
  contain &amp; and &lt;.
</p>

It’s not quite automatic, but might reduce the editing required.

like image 119
matt Avatar answered Apr 09 '23 05:04

matt