Using simple_format and html_safe at the same time in Rails
Asked Answered
B

2

12

In the @post.content, I want

1.simple_format, so content would have different lines rather than in a single line without breaks

2.html_safe, so user could paste some <embed> video link like youtubes

It's OK to use <%= simple_format @post.content %> and <%= @post.content.html_safe %> separately

But when I use them together: <%= simple_format @post.content.html_safe %>, html_safe is not working, and hence the <embed> video is not displayed

Could you tell me how can I enable <embed>code and simple_format at the same time? or is there other solutions to display the @post.content? Thanks!!!

Borrow answered 23/4, 2013 at 11:55 Comment(4)
how about simple_format(@post.content).html_safe? this would call html safe on the output of simple_format rather than 'simple_formatting' the html_safe version of post.content.Wristlet
uhm....It's still not working....Borrow
can you show the output of @post.content ?Wristlet
Same as simple_format @post.content.html_safe, no <embed> code is displayed. apneadiving's answer is workingBorrow
L
17

I'd tell simple_format not to sanitize my content:

simple_format(@post.content, {}, :sanitize => false)
Lesleelesley answered 23/4, 2013 at 12:4 Comment(0)
A
1

I am working on a similar problem.

I am trying to post code snippets in my blog post. It works pretty well but anything inside a <> gets stripped out. Whether I show or something more complex anything inside the <> disappears. I have run the <%= simple_format(@article.content), {}, sanitize: false code and I came close to getting what I wanted.

The problem was the code inside my blocks actually altered my page layout. :).

I wound up going with Redcarpet as my answer.

It's pretty simple.

Add gem 'redcarpet' to your Gemfile and restart your Rails server.

In the application_helper.rb put the following code:

def markdown(content)
  @markdown ||= Redcarpet::Markdown.new(Redcarpet::Render::HTML, autolink: true, space_after_headers: true, fenced_code_blocks: true)
  @markdown.render(content)
end    

The options here are described in the documentation. But, fenced_code_blocks: true is what allows you to put code in blocks as described.

That will output here whatever you type and it will work with your embed.

Then, to render it in your case just put:

markdown(@post.content).html_safe

Should be good to go. You also have the option to indent four spaces like here to insert code. It seems easier to do the fenced though.

Alternator answered 9/5, 2013 at 18:21 Comment(1)
This is similar to the solution above of simple_format(@post.content).html_safe and would work for the embed issue here. But, in my case I had Javascript and Coffeescript I wanted to show and doing the simple_format option showed it, but then the code inside my pre blocks reformatted my whole page.Alternator

© 2022 - 2024 — McMap. All rights reserved.