AbstractBrain Answers About us →

How to render markdown views in Rails

Question

I would like to use markdown instead of HTML in my Rails views. The problem is that markdown views are not rendered and the raw markdown code is returned as is. How can I solve this? How can I return the rendered HTML from markdown files?

Answer

In order to add markdown support to Rails, you just need to add a simple initializer to your application (less than 10 lines of code):

# config/initializers/markdown_handler.rb

class MarkdownHandler
  def call template, source
    markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, fenced_code_blocks: true)
    markdown.render(source).inspect
  end
end

ActionView::Template.register_template_handler :md, MarkdownHandler.new

Also remember to add the redcarpet gem to your Gemfile and to restart your server.

Finally you can create your views with the .html.md extension (the .html part tells Rails that you want to output HTML code).