karlherrick.com

Code Highlighting

Sunday, 13 December 2020

It seemed like a neat idea to encapsulate syntax highlighting responsibilities for the various code snippets that I share at times, so I went ahead and wrote a custom element to help me take care of the job. To try it out, install x-postpress-code with your favorite package manager and import into your project. If you like going buildless [1, 2], load it from a CDN like unpkg or skypack:

<script
  src="https://unpkg.com/x-postpress-code@1.0.3"
  type="module"
></script>

Once registered, the web component requires a type attribute to identify which supported language should be highlighted. The content of the code itself can either be lazy loaded using the src attribute, or by including the source in the default slot surrounded by pre tags:

<x-postpress-code type="bash"><pre>
#/usr/bin/env bash
for file in *; do
  echo $file
done
</pre></x-postpress-code>

One nice side effect of defining the code this way, is that if JavaScript is disabled for whatever reason, the original is still rendered (although unhighlighted). Try it out at JS Bin, or checkout the project page for more information.


Home

About

Portfolio

Web Apps Web Enabled Applications Corporate Sites Personal Sites
Preferences Dark Theme Light Theme Notifications
Social GitHub LinkedIn RSS Feed Icon