This recipe explains how to add source code highlighting to a Scroll Viewport theme.
This is necessary because Scroll Viewport does not format the content of a code macro by default. Instead, theme developers can use a source code highlighter of their own choice. This recipe documents how to use the Prism and Prettify highlighters.
Code Highlighting with Prism
Prism is an open source modular source code highlighter written in JavaScript. It can be themed using CSS.
To use it in a Scroll Viewport theme, firstly create a macro override template that overrides the rendering of the code macro (by convention this should be located in the overrides
directory in the template):
overrides/code.vm
<pre><code class="language-$params.language">$stringEscapeUtils.escapeHtml($body)</code></pre>
CODE
Go to the download section of Prism and select theme and the languages you want to format. Then download the files and put them in their appropriate folder within the Viewport theme.
Now, you can embed them in your page.vm as shown below:
## load the link to the CSS theme (in the HTML header)
<head>
<link href="${theme.baseUrl}/assets/css/prism.css" rel="stylesheet">
</head>
## load the JS file (usually at the end of the template)
<script src="${theme.baseUrl}/assets/js/prism.js"></script>
XML
Code Highlighting with Prettify
Prettify is a source code highlighter written in JavaScript. It can be themed using CSS.
To use it in a Scroll Viewport theme, firstly create a macro override template that overrides the rendering of the code macro (by convention this should be located in the overrides
directory in the template): overrides/code.vm
<pre class="prettyprint linenums">$stringEscapeUtils.escapeHtml($body)</pre>
CODE
Now, register the macro override when rendering the content (in blog.vm and all page templates, replace $page.content
with the following):
$page.renderContent("layouts/layout12.vm", {
"code" : "overrides/code.vm"
}))
CODE
Then, add the references to prettify.js and the CSS file:
## load the link to the CSS theme (in the HTML header)
<link href="${theme.baseUrl}/assets/css/prettify-tomorrow.css" rel="stylesheet">
[...]
## load the JS file (usually at the end of the template)
<script src="${theme.baseUrl}/assets/js/prettify.js"></script>
CODE
Finally, call prettify when the document loads:
<body onload="prettyPrint()">
[...]
</body>
CODE
Next steps
Please also read Advanced Content Rendering for more information about macro overrides.