Jake
Jake

Reputation: 1370

Replace html_safe with content_tag in Rails

So I'm working on a pretty simple project. We have the following coming in for a post's content: "Here is some text".

Right now it looks like this in the view:

<%= raw @post.content %>

This works perfectly but it's failing in lint with a warning "Tagging a string as html safe may be a security risk, prefer 'safe_join' or other Rails tag helpers instead.

So I moved to using:

<%= @post.content.html_safe %>

Same lint warning. I tried using h @post.content but I get all the HTML crud.

So then I switched to:

<%= content_tag @post.content %> 

Works except it displays the following: <"Here is some text">

So 1. Why is it displaying them? 2. How do I get rid of them? Is content_tag the best replacement for raw?

Upvotes: 2

Views: 5588

Answers (2)

Jake
Jake

Reputation: 1370

Not really an answer to why but in this situation using the following resolved the issue:

<%= sanitize @post.content %>

Upvotes: 4

Jay-Ar Polidario
Jay-Ar Polidario

Reputation: 6603

  • html_safe and raw will NOT ESCAPE the string.
  • NOT using either of the above WILL ESCAPE the string.

So.

<%= raw "<script>alert('hello world!')</script>" %>

and

<%= "<script>alert('hello world!')</script>".html_safe %>

... will pop-up a "hello world!' dialog box, and thus dangerous as they can write any script here or add DOM elements to the page.

Not using them, and just using <%= %> will escape the string, and is what you'd instead want:

<%= "<script>alert('hello world!')</script>" %>

... will show &lt;script&gt;alert(&#39;hello world!&#39;)&lt;/script&gt; on the page instead of popping an alert box; and thus safe.

Upvotes: 0

Related Questions