Rails: Render Markdown Views and Partials

kinopyo avatar

kinopyo

Assume you have a markdown contents saved in a partial _about.md and you want to render it in your view.

# About me

I'm a writer.
# won't work as-is

Custom Template Handler

First, you would need to register the type/extension of .md and map it into a customized handler - let's call it MarkdownTemplateHandler. I'm putting it under lib folder but you can put wherever you want, even inside the same initializer file is alright.

require Rails.root.join("lib", "markdown_template_handler")

ActionView::Template.register_template_handler(:md, MarkdownTemplateHandler.new)

Then the handler class. (Change the redcarpet markdown renderer to the one you picked.)

class MarkdownTemplateHandler
  def call(template)
    markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML)

    "#{markdown.render(template.source).inspect}.html_safe;"
  end
end

That's it! In your view, you can render it just like normal partials.


It also works with direct views (not partials).

# About me

- Writer
- Dreamer

Dive into Rails

You may wonder why the weird syntax of inspect and html_safe. Glad you ask!

It's actually the same as ActionView::TemplateHandlers::Raw#call. The return value of our customized handler#call will be eval'd here in ActionView::Template#compile.

If you're interested, you can check how other template handlers (erb, html, etc) are implemented under action_view/template/handlers in the Rails repo.

Using Existing Gems

Alternatively, you can drop one of these gems to get the same functionality quickly:

I prefer the in-house solution in this case as it's simple enough and also provides flexibilities to render the markdown (not tight to a specific gem & reuse my own preference).

Markdown, can't live without it now πŸ˜€.

kinopyo avatar
Written By

kinopyo

Indoor enthusiast, web developer, and former hardcore RTS gamer. #parenting
Published in Rails
Enjoyed the post?

Clap to support the author, help others find it, and make your opinion count.