How to Add Code Syntax Highlighting to Your Website

Hey Butter users! Did you know that you can highlight your code syntax in ButterCMS! With this feature, your code snippets in your blog posts will stand out and be much easier to read.

Let's show you how to do this.

The first step is to insert your code snippet.

undefined

Here's a sample piece of code I added:

require 'json'

module ButterCMS
  module Parsers
    class Posts

      def initialize(response)
        @response = response
      end
      
      # Returns the number of the next page or nil if not available
      #
      # @return [String]
      def next_page
        parsed_json['meta']['next_page']
      end
      
      # Returns the number of the previous page or nil if not available
      #
      # @return [String]
      def previous_page
        parsed_json['meta']['previous_page']
      end
      
      # Returns the count of existing posts
      #
      # @return [String]
      def count
        parsed_json['meta']['count']
      end
      
      # Returns array of posts attributes available in the response
      #
      # @return [Array]
      def posts
        parsed_json['data']
      end

      private

      attr_reader :response

      def parsed_json
        @parsed_json ||= ::JSON.parse(response.body)
      end
    end
  end
end

Once you add the code sample and save it, this plain code syntax is what you'll currently see when you preview your draft:

undefined

To highlight this code syntax, head over to the source code. You'll notice some tags with <pre class="language-undefined"> which isn't needed. Search for class="language-undefined" in your source code and erase them. Once you erase it, all <pre class="language-undefined"> should now be <pre>.

undefined

Discover how ButterCMS works with any tech stack.

Make sure to save this and now when you preview your draft, your new highlighted code syntax should be visible!

undefined

You can also use this method to edit your previous posts and update the code syntax on those as well! Happy blogging!

Still have a question?

Our Customer Success team is standing by to help.