Adding syntax highlighting

Our themes allow you to present code in styled blocks using the article editor, but you may wish to apply additional syntax highlighting.

Syntax highlighting is a way of using different colors and/or fonts to improve the readability and context of the code. By default code blocks within the article content of our theme appears without syntax highlighting.

<pre>.a-class-name {<br>  color: red;<br>}</pre>

Custom code highlighting

The highlight.js library is a quick and easy way to automatically add syntax highlighting to your code examples, based on a dynamically detected language. To add the library to your theme:

  1. Select a highlight.js theme from the many available on the highlight.js demo page.

  2. Link to the appropriate stylesheet to your theme’s document_head.hbs template. For example, if your chosen highlight.js theme is “Paraiso Dark”, the stylesheet code would be:

     <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.5.1/build/styles/paraiso-dark.min.css">
    

    To apply other highlight.js themes, replace paraiso-dark with the lowercase, hyphen-separated version of your chosen theme name.

  3. Add a reference to the required highlight.js JavaScript file in your theme’s footer.hbs template:

     <script src="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.5.1/build/highlight.min.js"></script>
    
  4. Add the following code to the ready() function in your theme’s script.js file:

     ready(function() {
       document.querySelectorAll('.content pre').forEach(el => {
         hljs.highlightElement(el);
       });
          
       // The rest of your theme's scripts are here..
     });
    

    You can update the selector to target subsets of your code blocks, for example <pre> elements with a class name of code could be targeted using .content pre.code.

Code examples added through the Zendesk article editor will then be updated with the appropriate highlighting. For example, a simple CSS declaration:

<pre>.a-class-name {<br>  color: red;<br>}</pre>

Questions or feedback about this article? Let us know