How to format your code samples with Prism JS
As a web blogger, you'll definitely have to display code samples in the articles you publish. You could use PRE elements to preserve the indentation and formatting, but it doesn't look great (even with some help from CSS):
if(x < 7){ alert("foo!"); }
HTML code samples can be tricky to display in PRE elements because you have to replace all the angle brackets (< and >) with entity characters.
<h1>Hello World!<h1>
A better way to have great looking code samples in your site is to use a library for syntax highlighting. In this article, I'll show you how to get started with PrismJS, which is a JavaScript and CSS library for displaying code samples in your web pages.
Installing Prism
To get started, go to the PrismJS download page and choose a few options to customize your download. This list will guide you through the options:
- Choose the development version if you want to download the source code in a readable format. The minified version is ideal for your live server because it is compressed to reduce it's file size, which helps to speed up the load time of the web that uses the Prism library. But the code in the minified version is unreadable because all of the tabs, extra spaces, and line breaks are removed from the code. If you are just playing around the PrismJS, you could choose either version.
- Choose your theme. Unfortunately you have scroll to the bottom of the page to preview the theme that you choose.
- Choose the languages that you will displaying in your code samples. For this class you can just leave the default selected languages, which are Markup (this includes HTML), CSS, C-Like, and JavaScript.
- If you scroll down past all the language options, you'll see that you can choose to include various plugins in your download. We'll make use of two of them, choose Unescaped Markup and Normalize Whitespace.
At the bottom of the page you'll see two buttons, one to download the Prism stylesheet, and the other to download the JavaScript file. Download these two files and then put them in the appropriate folders of your website. Now all you need to do in order use the Prism library in a web page is link to both files.
Now your code samples will look like this:
if(x < 7){
alert("foo!");
}
Using Prism
To add a code sample to a page, just add these tags:
<pre>
<code class="language-js">
// Your code sample goes here
</code>
</pre>
Note that you must set the class attribute of the CODE element to indicate the languague of your code sample. Set the class to a value of language-markup for HTML code samples. Use language-js for JavaScript code samples. And use language-css for CSS code samples.