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.
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:
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
.