Displaying code in HTML
There is a common need to display code in HTML or even to display HTML code inside HTML, especially in technical documentation or blogs. This has been done far too many times by taking an image from a piece of formatted code and making it part of the page. The code in the image will probably not get picked up by search engines. Additionally, it can limit us to a specific page layout or even screen size, and with today's mobile revolution, that is just not an option.
Getting ready
The only requirement for this recipe is that the data that will be displayed needs to be properly escaped; this means that <p>awesome </p>
needs to be translated into <p>awesome </p>
. This can be done either on the server side or escaped before saving.
How to do it...
We will be using Google code prettify because, at the time of speaking, this library is not available completely on any of the CDN's; you can get it from http://code.google.com/p/google-code-prettify/.
Afterwards, we can add the escaped code in the
<pre /> <code />
block:<body onload="prettyPrint()"> <div> <pre class="prettyprint"> <code> SELECT * FROM Book WHERE price < 100.00 ORDER BY name; </code> </pre> </div> </body>
Either one of these two tags has to include the
prettyprint
CSS class. In addition to that, we need to include theonload="prettyPrint()"
attribute.There is also the option to call the
prettyPrint
function from other event listeners added in JavaScript:<script> window.addEventListener('load', function (e){ prettyPrint(); }, false); </script>
How it works…
The prettyprint
class automatically selects all the blocks marked with the appropriate CSS class, and autodetects the programming language used, and does the highlighting afterwards.
The lexer should work on most languages; in the common languages there are custom scripts for specific languages, for example, for the lisp-based ones.
There's more…
Because prettyprint
automatically detects the source language, we could additionally specify it ourselves if we want to get better results. For example, if we wanted to display XML, the code would be as follows:
<pre class="prettyprint"><code class="language-xml">...</code></pre>
There are CSS classes for most of the common languages.
prettyprint
is one of the older scripts available, and there are few alternatives that can offer many more customization options and better JavaScript APIs.
Some of them, such as SyntaxHighliger (http://alexgorbatchev.com/SyntaxHighlighter/), Rainbow (http://craig.is/making/rainbows), and Highlight.js (http://softwaremaniacs.org/soft/highlight/en/), are commonly found on most of the sites.