Rails + Markdown + Syntax Highlighting
This post is to help you add syntax highlighting to your markdown in a rails app. I prefer to use [Redcarpet] for markdown processing, and [Rouge] for syntax highlighting. This is a complete ruby solution, I believe its the [fastest], and somewhat easy to implement.
Steps
- Add the
redcarpet
gem. - Build a
MarkdownParser
class to handle parsing our markdown. - Add the
rouge-rails
gem. - Build a
RougeRenderer
class to handle syntax highlighting. - Use the
RougeRenderer
class as the Redcarpet mardown renderer. - Set up your styleheets.
- Display the parsed markdown with syntax highlighting in code blocks
Add the redcarpet Gem
# Gemfile
gem "redcarpet"
MarkdownParser Class
# app/models/markdown_parser.rb
class MarkdownParser
require "redcarpet"
def initialize(markdown)
@markdown = markdown
end
def markdown_to_html
processor.render(@markdown).html_safe
end
def processor
Redcarpet::Markdown.new(renderer, extensions = {})
end
def renderer
Redcarpet::Render::HTML
end
end
Add the rouge-rails Gem
# Gemfile
gem "rouge-rails"
RougeRenderer Class
# app/models/rouge_renderer.rb
class RougeRenderer < Redcarpet::Render::HTML
require "rouge"
require "rouge/plugins/redcarpet"
include Rouge::Plugins::Redcarpet
end
Use RougeRenderer As Redcarpet Renderer
# app/models/markdown_parser.rb
class MarkdownParser
...
def renderer
RougeRenderer.new(render_options = {})
end
end
Styelsheets
There are a couple of ways to add the code styles to you rails app. I like to
use the rouge rougify
CLI command to generate a stylesheet. The CLI command
should let you generate any theme found in the rouge gem's [themes].
[themes]:https://github.com/jneen/rouge/tree/master/lib/rouge/themes
For example, to generate a github stylesheet:
$ rougify style github > app/assets/stylesheets/github.css
Then add it to your application.scss
file.
# app/assets/stylesheets/application.scss
@import "github";
You can also copy a stylesheet from [here], but be aware of how the classes are scoped. You will have to set up Rogue to handle themes.
[here]:https://github.com/jacobsimeon/rouge-rails/tree/master/app/assets/stylesheets/rouge
Use it
Pass the markdown parser a file:
<%- file = File.read("path/to/file.md") %>
<%= MarkdownParser.new(file).markdown_to_html %>
Pass the markdown parser text:
<%= MarkdownParser.new("#heading ```code {} ```").markdown_to_html %>
Resources:
[Redcarpet]:https://github.com/vmg/redcarpet [Rouge]:https://github.com/jacobsimeon/rouge-rails [fastest]:https://www.sitepoint.com/markdown-processing-ruby/