## Prism For Code Samples

Sept 1, 2020 by Niall K.

This article will get you up and running with the Prism code highlighter in no time.

### Why use Prism?

As a web developer and a blogger, you'll probably be displaying lot's of code samples on your pages. By now, you probably already know how important it is to format and indent your code properly. I always tell my students that if you can't format code properly by the second semester, then don't tell anyone I was your teacher! So the code samples you put on your blog posts should be formatted perfectly as well. Here's an example:

In HTML, extra white spaces are ignored, but you can use a PRE to overcome this and keep all your spacing intact.

    let x = prompt("Enter a number");

    if(x == 7){
        alert("Lucky number 7!");
    }

As you can see, the formatting looks OK, but it's a bit hard to look at the code. Wouldn't it be great if you could make the code look just like it does in your IDE, with all the highlighting to help you read and understand it? That's where Prism comes into play. Here's the same code sample as the previous one, but it uses Prism.

    let x = prompt("Enter a number");

    if(x == 7){
        alert("Lucky number 7!");
    }

### Downloading and Installing Prism

Here are the steps you'll need to take to put Prism to work on your website:

- Download the files for Prism at this page. Scroll to the bottom of the page and download both the .js file and the .css file.
- Put these two files in the appropriate folders for your website.
- Add links to these two files in the pages that will include code samples. I actually have these links in all the pages for my website.
- Start adding code samples.

### Adding Code Samples to Your Pages

To add a code sample you'll need to add a PRE tag to your page and then nest a CODE tag inside of it. Also, you'll have to add a class attribute to the PRE tag which will tell Prism which language you are using for your sample code. If you want to add JavaScript code, set the class attribute to a value of language-js like this:

    <pre class="language-js"><code>
    let x = prompt("Enter a number");

    if(x == 7){
        alert("Lucky number 7!");
    }</code></pre>

I know some of you are ready to jump all over me right now because the code doesn't appear to be formatted properly (I'm always on your case about indenting your code!). But remember that you'll have to break some of the rules if indenting when you are using PRE tags.

If you want to display a code sample in another language, like HTML, then you'll set the class attribute of the PRE tag to language-html. You can figure out which suffix to use by looking at the download page that was discussed earlier.

When displaying HTML code sample in your HTML web pages, you'll have to use entity characters for the angle brackets, otherwise the code sample will be interpreted as real HTML code.