Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: how to render a string as HTML?

People also ask

How do I render a string in HTML?

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).

Can you use Ruby in HTML?

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.

What does Html_safe do in Rails?

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.

What is render partial in Rails?

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.


UPDATE

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