Monday, December 26, 2016

How to apply code syntax highlighting on html page

As a programmer I include examples of source code to pages of my blog. I'd like to have a nice syntax highlighting of this fragments of code. Here I'll show yoг how to do it.

To get support of syntax highlighting I'll use highlight.js library. It is very flexible. At the moment the library supports 167 programming languages and 77 different styles of highlighting. One may compile version of JavaScript file which includes only desired set of languages. Also highlight.js is available as Node.js package and as ready files from several CDNs.

To include support of syntax highlighting on your html page you need only 3 lines of code:

<link href='//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/styles/agate.min.css' rel='stylesheet'/>
<script src='//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/highlight.min.js'/>
<script>hljs.initHighlightingOnLoad();</script>

Now you can insert fragments of your code to the page. Just enclose them in <pre><code> tags:

<pre><code class="cs">public static TValue GetOrDefault<TKeyTValue>(this IReadOnlyDictionary<TKeyTValue> dictionary, TKey key,
    TValue defaultValue)
{
    TValue result;
    if (dictionary.TryGetValue(key, out result))
    {
        return result;
    }
    return defaultValue;
}</code></pre>

If you want to change highlighting schema just replace agate.min.css in <link> tag with any other schema. List of schemas with examples you can find here.

In the end I'll explain how you can add this support to a blog on Blogger platform. Open your blog for editing and go to "Template" section. Click on "Edit HTML" button:


Add the 3 lines of code just before closing </head> tag:


Then click "Save template" button.

That's it! You have highlighting of code syntax in your blog!

No comments:

Post a Comment