Adding syntax highlighting to a Rails app with PrismJs
Rails PrismJs

Published on 11/10/2021 by Jerry Weyer

If you are running a technical blog, it is very likely that you want to share some code-snippets. Syntax highlighting is nearly a must in order to make any shared code readable for your audience. There are different solutions to integrate syntax highlighting into a Rails application - I'll quickly show how I integrated Prism into this blog.

The first step to get syntax highlighting for your code snippets is to use the correct HTML tags. It is generally advised to add your snippets in a

<pre><code>...</code></pre>block.

Next we will add code highlighting with the javascript library Prism. There are other options (like highlightjs), but Prism was the fastest to get running on this Rails blog app.

First we add Prism via yarn package manager: yarn add prismjs.

Then we add the plugin to our babel.config.js and define the languages we want to import:

  
  plugins: [
    ["prismjs", {
      "languages": [ "css", "ruby"]
    }],
  

You can find a list of supported languages on the Prism website.

Finally, in order to load the script after page load, we update our application.js:

  
  import Prism from 'prismjs'

  document.addEventListener("turbo:load", function() {
       Prism.highlightAll();
  });
  

If your app runs turbolinks instead of turbo, you need to change the "turbo:load" to "turbolinks:load".

This should be enough to get the basic syntax highlighting working! You can now customize your integration:

You can add custom styling by simply overriding the theme styling in your css files, e.g. to change the background color:

  
  :not(pre) > code[class*="language-"],
  pre[class*="language-"] {
      background: #334155 !important;
  }
  

You can add custom themes via the prism-themes repository. Add the plugin via yarn add prism-themes and import the corresponding theme in your application.scss with @import "prism-themes/themes/prism-dracula.css";. This blog uses a slightly customizes version of the dracula theme.

Please head to the dev.to article if you want to comment or discuss this post.

Home