DEV Community

Jerry Weyer
Jerry Weyer

Posted on • Updated on • Originally published at jerryweyer.lu

Adding syntax highlighting to a Rails app with PrismJs

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"]
    }],
Enter fullscreen mode Exit fullscreen mode

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();
  });
Enter fullscreen mode Exit fullscreen mode

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;
  }
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (2)

Collapse
 
lioness100 profile image
Lioness100

Oooh this is useful. Thanks for the tip! 🎉

Collapse
 
jerryweyer profile image
Jerry Weyer

Good to hear, let me know if it works or you encounter any problems!