Web Dev

Render Markdown in Rails with Redcarpet and SmartyPants

Rendering Markdown in your Rails app is pretty simple, thanks to the Redcarpet gem. We’ll set up a helper to render markdown in our views.
 
 
 
 
 
 
 
 
 
 
First, add the following to your Gemfile and then run bundle install:

gem 'redcarpet'

Now, let’s create a helper to render markdown in our views:

# app/helpers/application_helper.rb

module ApplicationHelper
  def markdown(content)
    @markdown ||= Redcarpet::Markdown.new(Redcarpet::Render::HTML, {
      autolink: true,
      space_after_headers: true,
      fenced_code_blocks: true,
      underline: true,
      highlight: true,
      footnotes: true,
      tables: true
    })
    @markdown.render(content)
  end
end

The ||= operator keeps the Markdown generator from being instantiated each time the helper is called. Instead, it is saved as an instance variable. The markdown text is passed into the helper as a string, and HTML is returned. You can now use the helper in your template like so:

<%= markdown(@post.body).html_safe %>

That’s it! Note, that we call html_safe so that the resulting HTML isn’t escaped.

You can certainly stop here, but one thing that bugs me is that apostrophes, quotes and dashes are not turned into the typographically correct &apos; &lquo; &rquo; &ndash; and &mdash; entities. This can easily be fixed using SmartyPants, which is included with Redcarpet as a post-processing step. To do this, we need to subclass Redcarpet::Render::HTML, Redcarpet’s Markdown rendering class. Create the following file:

# app/services/blog_markdown_renderer.rb

class BlogMarkdownRenderer < Redcarpet::Render::HTML
  include Redcarpet::Render::SmartyPants
end
# app/helpers/application_helper.rb

module ApplicationHelper
  def markdown(content)
    @markdown ||= Redcarpet::Markdown.new(BlogMarkdownRenderer, {
      autolink: true,
      space_after_headers: true,
      fenced_code_blocks: true,
      underline: true,
      highlight: true,
      footnotes: true,
      tables: true
    })
    @markdown.render(content)
  end
end

Now, when you render markdown, all your quotes and dashes are converted to HTML entities. Nice!

Reference: Render Markdown in Rails with Redcarpet and SmartyPants from our WCG partner Steve Hanson at the CodeTutr blog.

Steve Hanson

Steve is a software developer interested in web development and new technologies. He currently works as a Java consultant at Credera in Dallas, TX.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button