1
votes

I'm using slim in my rails app to generate my views, and have enabled the markdown engine (with redcarpet) so I can write markdown in my slim files like so:

h2#usage Usage
markdown:
    ### Via JavaScript

    Call the dropdowns via JavaScript:

    ```js
    $('.dropdown-toggle').dropdown()
    ```

I've also enabled fenced code blocks in my config/initializers/slim.rb:

Slim::Embedded.default_options[:markdown] = {
  fenced_code_blocks: true
}

My question is, how how do I configure either redcarpet or another gem to generate syntax highlighting for the fenced code blocks in my markdown? I've looked into pygments and rouge, but I'm a bit lost.

2

2 Answers

4
votes

Stitching together a few things here:

You can use the rouge gem for highlighting source code. It's pretty easy and well documented how to use it with Redcarpet. Getting Slim to use your renderer is the tricky part, but the luckily others have already fought this battle: a pretty old github issue and a resulting blog post

require 'rouge/plugins/redcarpet'

class HTML < Redcarpet::Render::HTML
  include Rouge::Plugins::Redcarpet # yep, that's it.
end

Slim::Embedded.set_default_options markdown: {
  renderer: HTML.new,
  fenced_code_blocks: true
}

I haven't tested this, so the code might need some tweaking.

0
votes

A quick update - since Slim's API had changed...

I used the following code that worked for me, it both addresses the change in Slim's API and addresses the issue of the named class disrupting the namespace.

require 'rouge/plugins/redcarpet'
Slim::Embedded.options[:markdown] = {
        fenced_code_blocks: true,
        renderer: (Class.new(Redcarpet::Render::HTML) {include Rouge::Plugins::Redcarpet} ).new
    }

Thank you @tmichel for the original answer.