Markdown & Syntax Highlighting
Written by Luka Kerr on April 1, 2018
To implement markdown with syntax highlighting into your Rails application, you need two Ruby gems; redcarpet
a markdown parser and pygments.rb
a Ruby wrapper for a Python syntax highlighter.
To get started, simply add the following two lines into your Gemfile
and run bundle install
:
gem 'redcarpet'
gem 'pygments.rb'
Next we need to create a helper method, so that we can use a simple function in our views. Lets create this method inside the /helpers/application_helper.rb
file.
module ApplicationHelper
class HTMLwithPygments < Redcarpet::Render::HTML
def block_code(code, language)
Pygments.highlight(code, lexer: language)
end
end
def markdown(text)
renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: true)
options = {
autolink: true,
no_intra_emphasis: true,
fenced_code_blocks: true,
lax_html_blocks: true,
strikethrough: true,
superscript: true,
}
Redcarpet::Markdown.new(renderer, options).render(text).html_safe
end
end
For the markdown()
function, we use a hash to add markdown extensions such as autolink
. You can find more extensions here.
Next we need to create a file inside /assets/stylesheets/
called pygments.css.erb
and paste just the following line into that file:
<%= Pygments.css(style: "monokai") %>
This example uses the monokai
syntax highlighting style, but there are many more options to choose from.
Finally, in our views file, such as show.html.erb
, simply include the markdown()
function before any database call that includes text. For example, if you’re using a Post
model and want to fetch the post body, use the following line:
<%= markdown(@post.body) %>
Make sure to restart your server as well.
Once this is all done, simply create a new post, and style it using markdown and include a programming language’s syntax you like, the results speak for themselves.