Display Code On Your Blog With Highlight.js & Prettify (Syntax Highlighters)

Syntax highlighting helps improve the readability of the code that you display on your webpages and makes the code standout from the rest of the text. A number of excellent Syntax Highlighters are available online for free. Google code project “Prettify” and "Highlight" are two excellent, lightweight code highlighters which you can use on your blog. Both include support for the most commonly used languages.

Using Prettify


The Prettify script is hosted on Google, so you don't even need to host it on your end. Simply add the following code before the closing </head> tag in your template:
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js">
Marking code sections:

Now whenever you display code on your page, simply enclose it in <pre>...</pre>, <code>...</code> or <xmp>...</xmp> tags with a class of "prettyprint". Here's an example:
<code class="prettyprint">
...YOUR_CODE_HERE...
</code>
Selecting Styles:

If you don't like the default skin, there are 4 other styles you can choose from (Available here):
<script codearea2="" src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js?lang=css&amp;skin=SKIN_NAME></script>
To select a different skin, change SKIN_NAME in the code above with the actual skin name. Available skins include: doxy, sons-of-obsidian, sunburst and desert.

Using Highlight.js


Just like Prettify, highlight.js is another great syntax highlighter for the web that you can use to make your code look beautiful. Plus, it offers a lot of styles to choose from. To use highlight.js, add the following code before the closing </head> tag in your template.
<link href="http://yandex.st/highlightjs/8.0/styles/default.min.css" rel="stylesheet"></link>
<script src="http://yandex.st/highlightjs/8.0/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoadundefined);</script>
Marking code sections:

Using the code above will highlight all code you display within
tags in your post
<pre><code>
...
</code></pre>


Selecting Styles:

You can select from 44 different styles. For available style names look into the highlight.js styles directory (don't forget to add ".min" before ".css").

Once you have selected a style, here's how you can apply it to the code:

<link href="http://yandex.st/highlightjs/8.0/styles/ascetic.min.css" rel="stylesheet" type="text/css"></link>

That's it! Your code should now look neat and standout from the text.

2 comments :

Reader's Comments

  1. How to subscribe for your site? Please suggest

    ReplyDelete
    Replies
    1. Thank you for your interest. If you found anything useful, you can bookmark or subscribe to the feeds. Here's the URL: http://techmarshal.blogspot.com/feeds/posts/default

      Delete