Skip to main content

How to Add Code Snippet Syntax Highlighting Your Plone Theme

June 23, 2016

This example is using highlightjs.

First off, start include the js and css in your theme html file in the head section:

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.4.0/styles/default.min.css">

 

Then at the bottom of the theme file, before the closing body tag, add the JavaScript dependency.

<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.4.0/highlight.min.js"></script>

If you're on Plone 5, you'll need to include this just before the JavaScript file because highlight js is expecting requirejs compilation:

<script>
original_define = define;
define = undefined;
</script>

Then, the glue JavaScript code:

<script>
$(document).ready(function() {
$('pre').each(function(i, block) {
hljs.highlightBlock(block);
});
});
</script>

This example will automatically transform all pre tags. You can change it to use "code" or any other tag that makes more sense for your site. You can also customize the selector to only work for particular page types or views.

The whole JavaScript integration script will look like this for Plone 5 when it's all put together(placed at the bottom of your html theme file):

<script>
original_define = define;
define = undefined;
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.4.0/highlight.min.js"></script>
<script>
define = original_define;
$(document).ready(function() {
$('pre').each(function(i, block) {
hljs.highlightBlock(block);
});
});
</script>