26

@post.body has following content (which is converted from Markdown by using RDiscount).How should I render it to the user in what it means? i.e I want to render it as strong text emphasized text...

<p><strong>strong text</strong> </p> <p><em>emphasized text</em> </p> <blockquote>  <p>this is a quote</p> </blockquote><p><img src="http://www.picturehouse.com/titles/images/rock.jpg" alt="alt text" title="" /> </p> 

Using <%= @post.body => will only display it as the text shown above.

CTS_AE
  • 12,987
  • 8
  • 62
  • 63
pierrotlefou
  • 39,805
  • 37
  • 135
  • 175
  • Since no post mentions it you can use `<%== @post.body %>` which is an alias to `<%= raw(@post.body) %>` https://edgeguides.rubyonrails.org/active_support_core_extensions.html#output-safety – CTS_AE Feb 12 '19 at 20:20

4 Answers4

56

Assuming Rails 3, use the raw helper method e.g.

<%= raw(@post.body) %>

Escaping HTML output is on by default in all view templates (in contrast to earlier versions where you had to use the h method to escape strings individually.)

AnkitG
  • 6,438
  • 7
  • 44
  • 72
mikej
  • 65,295
  • 17
  • 152
  • 131
  • Old thread, but how can you limit what tags are displayed? Ex block – StackExchange User Mar 02 '13 at 23:06
  • Take a look at the [sanitize](http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize) method or check out [Ryan Groves's Sanitize library](https://github.com/rgrove/sanitize) if you need more control. – mikej Mar 04 '13 at 17:35
5

Are you using rails 3? It automatically escapes all contents of <%= %> tags. To avoid it, do

<%= raw(@post.body) %>
alex.zherdev
  • 23,914
  • 8
  • 62
  • 56
5

I take it you're in Rails 3? One big change is that displayed text used to be raw by default, and you had to sanitize it yourself. Now it's the other way around. Call it like this:

<%= raw(@post.body) %>

And you'll get what you're looking for.

Jaime Bellmyer
  • 23,051
  • 7
  • 53
  • 50
3

Quick, Easy, & to the Point

<%== @post.body %>

More Information

<%== @post.body ==> is an alias to <%= raw(@post.body) ==>

https://edgeguides.rubyonrails.org/active_support_core_extensions.html#output-safety

CTS_AE
  • 12,987
  • 8
  • 62
  • 63