How can I automatically render partials using markdown in Rails 3?

Jacob picture Jacob · Nov 12, 2010 · Viewed 11.3k times · Source

I want to have some of my partials as markdown snippets. What is the easiest way to render them using the standard rails erb templating?

Ideally, I'd like to do something like this:

If I have a partial in app/views/_my_partial.md.erb:

My awesome view
===============

Look, I can **use** <%= language %>!

which I reference from a view like so:

<%= render "my_partial", :language => "Markdown!" %>

I want to get output that looks like this:

<h1>My awesome view</h1>
<p>Look, I can <strong>use</strong> Markdown!</p>

Answer

Jacob picture Jacob · Apr 12, 2012

Turns out, the Right Way (tm) to do this is using ActionView::Template.register_template_handler:

lib/markdown_handler.rb:

require 'rdiscount'

module MarkdownHandler
  def self.erb
    @erb ||= ActionView::Template.registered_template_handler(:erb)
  end

  def self.call(template)
    compiled_source = erb.call(template)
    "RDiscount.new(begin;#{compiled_source};end).to_html"
  end
end

ActionView::Template.register_template_handler :md, MarkdownHandler

If you require 'markdown_handler' in your config/application.rb (or an initializer), then any view or partial can be rendered as Markdown with ERb interpolation using the extension .html.md:

app/views/home/index.html.md:

My awesome view
===============

Look, I can **use** <%= @language %>!

app/controllers/home_controller.rb:

class HomeController < ApplicationController
  def index
    @language = "Markdown"
  end
end