Using Markdown with Rails
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.
This is my solution
Gemfile
gem "redcarpet"
config/initializers/markdown_renderer.rb
module MarkdownRenderer
def self.markdown
@@markdown ||=
Redcarpet::Markdown.new(
Redcarpet::Render::HTML.new(
escape_html: true,
hard_wrap: true,
safe_links_only: true,
with_toc_data: true
),
autolink: true,
fenced_code_blocks: true,
no_intra_emphasis: true,
space_after_headers: true,
tables: true
)
end
def self.render(text)
markdown.render(text)
end
end
app/helpers/application_helper.rb
def markdown(text)
MarkdownRenderer.render(text).html_safe
end
your view
<%= markdown(@post.content) %>