Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using simple_format and html_safe at the same time in Rails

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!!!

like image 317
cqcn1991 Avatar asked Apr 23 '13 11:04

cqcn1991


2 Answers

I'd tell simple_format not to sanitize my content:

simple_format(@post.content, {}, :sanitize => false)
like image 74
apneadiving Avatar answered Nov 17 '22 03:11

apneadiving


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.

like image 1
Art Avatar answered Nov 17 '22 03:11

Art