Sinatra & HAML: automatically hide / convert unsafe HTML characters for the whole template?

I have a small sinatra app that I use to run a basic website. Content for the specified site is provided by the client, and most of it comes from PDF files. Since I don’t need to manually replace all < with &lt; & on &amp; Is there a way to configure HAML / Sinatra for this automatically for me?

Basically, I have a few 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 would just like to find the config option, which tells HAML to go through all the content and replace the unsafe characters with its copies of the HTML entity.

I tried using the HTMLEntities stone, but there are many multi-line paragraphs on this site, and I could not get it to work. By this, 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 he spat out a mistake about the lack of closure ) .

+4
source share
2 answers

You can use :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> 

This is not entirely automatic, but may reduce the required editing.

+6
source

Perhaps you are looking for this:

 require 'cgi' CGI::escapeHTML('unsafe string <script>kill() && destroy()</script>' #=> "unsafe string &lt;script&gt;kill() &amp;&amp; destroy()&lt;/script&gt;" 

EDIT

Now I really get what you want. Just use :escape_html => true , and you can wrap the text in ='...text here...' because all lines are implicitly escaped.

 require 'sinatra' get '/' do haml :index, :escape_html => true end __END__ @@layout !!! 5 %html %head %title Example %body = yield @@index %p ='Here is some <em>unsafe</em> HTML.' ='<script type="text/javascript">' ='killKittens() && destroyHumanity()' ='</script>' 

Result:

 $ curl localhost:4567 <!DOCTYPE html> <html> <head> <title>Example</title> </head> <body> <p> Here is some &lt;em&gt;unsafe&lt;/em&gt; HTML. &lt;script type=&quot;text/javascript&quot;&gt; killKittens() &amp;&amp; destroyHumanity() &lt;/script&gt; </p> </body> </html> 
+2
source

Source: https://habr.com/ru/post/1468733/


All Articles