One option to syntax-highlight some code in a web page is prism.js. I use it in some posts on this blog.

It's fairly simple to set up - but there's a trick to getting it to work from a CDN. When you download prism.js from the project website, a configuration tool lets you choose the languages you want included, then gives you a prism.js with only those languages included.

Importing support for the language you need

The version on cdnjs doesn't have a configuration tool - but rather than making a big file with all languages included, the base version includes a small set of languages, and other languages can be imported by including additional components.

The base version includes support for javascript, css, 'markup' (which works on HTML, XML, and XML-based things like SVG) and 'c-like'.

Languages that you haven't imported support for will be left unstyled - as if prism.js wasn't working at all. You have to explicitly import the language support files you need. As an example, here's how to style a bash script with prism.js from cdnjs:

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/prism/1.5.1/themes/prism.min.css">

page content goes here

<code class="language-bash">
#!/bin/bash
set -e # Exit on failure
# bash script here!
</code>

<script src="//cdnjs.cloudflare.com/ajax/libs/prism/1.5.1/prism.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/prism/1.5.1/components/prism-bash.min.js"></script>

Getting it to work with Jekyll

Follow this stackoverflow answer to adjust your post template to support extra_css, then include the required stylesheet in the YAML frontmatter:

---
layout: post
title: "Getting prism.js to work with Jekyll from a CDN"
description: ""
category:
tags: [programming, javascript, syntax highlighting, prismjs]
extra_css:
  - //cdnjs.cloudflare.com/ajax/libs/prism/1.5.1/themes/prism.min.css
---

Then just indicate any code blocks with triple-backticks:

```bash
#!/bin/bash
set -e # Exit on failure
# bash script here!
```

and the results should look like this:

#!/bin/bash
set -e # Exit on failure
# bash script here!

Congratulations! You (probably) now have prism.js syntax highlighting.



website@mjt.me.uk · Home · Archive · Tags