Skip to content

Instantly share code, notes, and snippets.

@nilliams
Last active January 24, 2020 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilliams/7138983 to your computer and use it in GitHub Desktop.
Save nilliams/7138983 to your computer and use it in GitHub Desktop.
Add client-side syntax highlighting to static sites (such as Jekyll w/ Pygments disabled), with Google-Code-Prettify.

Note: One alternative is to use this Prism.js Jekyll Plugin, the advantage of using google-code-prettify is that it can be used with standard markdown (indented code blocks) rather than using liquid tags like {% prism %}. Prettify will guess which language your code blocks contain and highlight appropriately.

Grab the google-code-prettify sources and include them in the <head> of your page template, for Jekyll you will want to edit layouts/default.html (tailor paths to directory structure):

<link rel="stylesheet" href="/css/google-code-prettify/prettify.css">
<script src="/js/google-code-prettify/prettify.js"></script>

This JS snippet adds the prettyprint class to <pre> tags and runs prettify:

<script>
  // 1. Add the `prettyprint` class to `pre` tags. - When using Jekyll you *could* omit this step 
  // by using {% highlight prettyprint %} in your posts (which adds it to the `code` tags),
  // *BUT:* 
  //  - The method used here allows you to keep posts markdown-only (just indent for code-blocks), for portability
  //  - {$ highlight %} tags seem to break with Pygments disabled anyway (i.e. if you put a `#` within a code-block)
  //  - the container styling fix in the following step will not be as straightforward
  [].forEach.call(document.getElementsByTagName("pre"), function(el) {
    el.classList.add("prettyprint");
  });
  
  // 2. Run
  prettyPrint();
</script>

(Optional) Less-cramped container styling:

<style>
  pre.prettyprint {
    padding: 8px 12px;
    border: 1px solid #bbb;
    border-radius: 4px;
  }
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment