DEV Community

Allan Simonsen
Allan Simonsen

Posted on

Sourcecode syntax highlighting in html with highlight.js

highlight.js example

In this article I will show you how to use the highlight.js JavaScript module to present your code beautifully syntax highlighted.

The code below is a simple html page with two source code samples in typescript and Python. The first example only has the plain source code. The second example shows the usage of the highlightjs-line-number addon that adds line numbers to the source code which makes it much easier to refer the lines in the code you want to show in your html page.

<html>
  <head>
    <!--Highlight.js: https://highlightjs.org/usage/-->
    <link rel="stylesheet" href="https://unpkg.com/@highlightjs/cdn-assets@11.3.1/styles/default.min.css" />
    <script src="https://unpkg.com/@highlightjs/cdn-assets@11.3.1/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/2.8.0/highlightjs-line-numbers.min.js"></script>
  </head>
  <body>
    <h1>Source code highlighting</h1>
    <h2>Typescript</h2>
    <pre name="source" id="source1" ><code id="source" class="language-typescript">
class MyClass {
    public static myValue: string;
    constructor(init: string) {
        this.myValue = init;
    }
}
import fs = require("fs");
module MyModule {
    export interface MyInterface extends Other {
        myProperty: any;
    }
}
declare magicNumber number;
myArray.forEach(() => { }); // fat arrow syntax
    </code></pre>
    <h2>Python</h2>
    <pre name="source" id="source2" ><code id="source" class="language-python">
@requires_authorization(roles=["ADMIN"])
def somefunc(param1='', param2=0):
    r'''A docstring'''
    if param1 > param2: # interesting
        print 'Gre\'ater'
    return (param2 - param1 + 1 + 0b10l) or None

class SomeClass:
    pass

    </code></pre>
    <script lang="javascript">
        var source1 = document.getElementById('source1')
        hljs.highlightElement(source1);

        var source2 = document.getElementById('source2')
        hljs.highlightElement(source2);
        hljs.lineNumbersBlock(source2, {
            startFrom: 1
        });
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Below you can see the result in the browser
Image description

You can read all the details about highlight.js and the highlightjs-line-number module here:

Top comments (0)