Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Markdown with Rails

I want users to type in Markdown text in a textarea and when they post it, I display the corresponding html. I read that Rails used to have a markdown method or similarly called method, that you could just call on that field in the ERB file:

<%= markdown(@post.content) %>

Apparently, Rails took that functionality out. What is the best way to get that functionality again? That seems to solve my need.

like image 450
at. Avatar asked Dec 22 '12 19:12

at.


1 Answers

I would use Redcarpet to do the markdown-html conversion. Also, I would move the conversion from the view to some other object. You could use callbacks (before_save) or use Observers.

From the docs:

markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML,
    :autolink => true, :space_after_headers => true)

markdown.render("This is *bongos*, indeed.")
#=> "<p>This is <em>bongos</em>, indeed</p>"

You probably want to store the result in another column, say @post.content_parsed so that the user can make later edits to the post, plus this way you don't need to make the conversion on every request.

like image 196
Jiří Pospíšil Avatar answered Sep 17 '22 20:09

Jiří Pospíšil