How to Enable Syntax Highlighting in Code Examples - Fluid Topics - Latest

Version
Latest
Category
How To
Audience
public

How to Enable Syntax Highlighting in Code Examples

Business need

Code samples included in published content are easier to read if syntax is properly highlighted.

Overview of the solution

This can be achieved by using a JavaScript customization tool such as the dedicated code library HighlightJS.

Adding custom JavaScript code to a tenant requires relevant technical skills and remains under the responsibility of the customer. Antidot will not support this code and cannot be held responsible for any service malfunction related to JavaScript customization.

Procedure

Custom JavaScript code must be provided to Fluid Topics Customer Service team so that it can be added to a test portal and then deployed to production.

Example

Below is an example of code syntax highlighting on the Fluid Topics documentation portal:

FT Doc Example

The Fluid Topics Doc Team chose the HighlightJS library to add styling data in order to colorize selected HTML paragraphs.

Custom.js code is used to load the lib and select which blocks it applies to. Since the HTML tags including code samples in Fluid Topics documentation are pre.codeblock p and pre.codeblock, the following JavaScript code has been added to the doc portal:

var hljsScript = document.createElement('script');
hljsScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js';
hljsScript.async = true;
document.head.appendChild(hljsScript);

var hljsStyle = document.createElement('link');
hljsStyle.href = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css';
hljsStyle.rel = "stylesheet";
document.head.appendChild(hljsStyle);

document.addEventListener('ft:reader:topicsloaded', function(event){
document.querySelectorAll('pre.codeblock p, pre.codeblock').forEach((block) => {
    hljs.highlightBlock(block);
    });      
});

After adding highlight.js tags, it is possible to apply new classes such as hljs-comment or hljs-string.

For more information, refer to the HighlightJS demo.