To render the html string in react, we can use the dangerouslySetInnerHTML attribute which is a react version of dom innerHTML property. The term dangerously is used here to notify you that it will be vulnerable to cross-site scripting attacks (XSS).
So far we've looked at using Ruby to create HTML output, but we can turn the problem inside out; we can actually embed Ruby in an HTML document. There are a number of packages that allow you to embed Ruby statements in some other sort of a document, especially in an HTML page.
html_safe actually "sets the string" as HTML Safe (it's a little more complicated than that, but it's basically it). This way, you can return HTML Safe strings from helpers or models at will. h can only be used from within a controller or view, since it's from a helper. It will force the output to be escaped.
Rails Guides describes partials this way: Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
For security reasons, it is recommended to use sanitize
instead of html_safe
.
<%= sanitize @str %>
What's happening is that, as a security measure, Rails is escaping your string for you because it might have malicious code embedded in it. But if you tell Rails that your string is html_safe
, it'll pass it right through.
@str = "<b>Hi</b>".html_safe
<%= @str %>
OR
@str = "<b>Hi</b>"
<%= @str.html_safe %>
Using raw
works fine, but all it's doing is converting the string to a string, and then calling html_safe
. When I know I have a string, I prefer calling html_safe
directly, because it skips an unnecessary step and makes clearer what's going on. Details about string-escaping and XSS protection are in this Asciicast.
If you're on rails
which utilizes Erubis — the coolest way to do it is
<%== @str >
Note the double equal sign. See related question on SO for more info.
Use raw:
<%=raw @str >
But as @jmort253 correctly says, consider where the HTML really belongs.
You can also use simple_format(@str)
which removes malicious code. Read more here: http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With