Ruby on Rails: How to Render a String as HTML

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

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.

How render HTML Link from String with Rails?

the plain text can be converted to html by called html_safe method on string.
Like '<a href="http//www.google.com">http//www.google.com</a>'.html_safe

Can I render a text string as a partial in Rails 3?

Looks like I just need to:

render :text => myTextFromS3, :layout => true

And it works!


Update: Since 2013 rails changed

There is 3 different ways:

render html: '<strong>HTML String</strong>' # render with `text/html` MIME type

render plain: 'plain text' # render with `text/plain` MIME type

render body: 'raw body' # render raw content, does not set content type, inherits
# default content type, which currently is `text/html`

Source https://github.com/rails/rails/issues/12374

Rails: Render HTML directly from controller.

You need to tell rails to render it as html content using .html_safe method. Try doing it like so:

render html: @htmldoc.html_safe

Render %= % as a String in an .html.erb View?

You should double the % symbols as follow:

<h3><%%= rating_color %></h3>

Edit for source:

In erb.rb line 50, we see that <%% is a special tag that is replaced by <% we can also see that on line 650.

dynamically render strings as html

You need to mark the string as 'html safe' in one of two ways:

<%= raw @string %>

... or by explicitly marking the string as html_safe:

<%= @string.html_safe %>

However: Please bear in mind that if this input comes from untrusted users (i.e. anyone other than you!), then this could be a risky strategy, as it will allow cross site scripting attacks. Make sure you read the rails security guide for more information on this risk and how to effectively mitigate it.



Related Topics



Leave a reply



Submit