Adding Code Blocks in Webflow CMS Blog Posts with highlight.js

HomeTutorials

I launched alexarias.io using Webflow because in my experience if you know about css, html, and javascript Webflow provides the most flexible and DRY (Don't Repreat Yourself) system out in the market. Unfortunately, I didn't find any built-in native functionality for formatted (colored) code blocks within their platform.

However, at the end of 2019 Webflow announced support for code blocks within rich text elements. With this new feature it's now easy to bring in third party js libraries to customize the look of specific sections inside blog posts. This is where highlight.js steps in!

highlight.js homepage

Adding this library is simple.

First add the required libraries to the head of the site: 

<!-- this stylesheet is the one that determines the color theme for all your code blocks -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.2/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.2/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

For a list of all the theme files available via CDN: https://cdnjs.com/libraries/highlight.js

The theme I use for my site is darcula: https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/styles/darcula.min.css

Go to the body section of your blog post. Place the cursor where you'd like to insert the formatted code block. You'll find a circle with a plus sign appear:

Click this symbol and you'll get a menu for adding rich elements:

Select the code block symbol " < > " and enter the code you'd like to be formatted along with the special opening and closing brackets highlight.js calls for:

highlight.js will render the code on your site like this:

print('hello world!')

To render HTML, you'll have to first escape the HTML code. There's an excellent Stack Overflow post on this: here.

Once you've escaped the html, you'll then be able to insert it in the code block:

And that's it!

Let me know if you found this useful or if something didn't work in the comments below!

Written by
Alex Luis Arias