Make HTML, C++, PHP, etc code colored on web pages

Ever wished you could color the source code of your programs on your html/web pages? Google makes it easy. All you need are two files and a little work: prettify.cs and prettify.js. These can be downloaded from Google and placed on your server or you can just reference them.

Step 1: Place the following source code between you're <head> and </head> tags:

<link href="http://google-code-prettify.googlecode.com/svn
/trunk/src/prettify/prettify.css" rel="stylesheet" type="text/css"/>
<script src="http://google-code-prettify.googlecode.com/svn
/trunk/src/prettify.js" type="text/javascript" />


If you downloaded the two files to your server, change the URLs above to point to the files you downloaded.

Step 2: Add onload="prettyPrint()" to your body tag (located just after the closing head tag usually) as follows:

<body onload="prettyPrint()">


Step 3: Google pretty print should now be working. If you want to "color" some code you just need to wrap it in <pre> tags as follows:

<pre class="prettyprint">"Test Code String"</pre>


and you should get:

"Test Code String"


Perhaps we should try something more exciting? How about a C++ snippet?

/* Test C++ comment and code snippet */
for ( int i = 0; i < 10; i++ ) {
cout << "Hello, World, ten times!" << endl;
}


Beyond step 3: Now what? Well, pretty print will automatically figure out what language you are trying to format. However, if you wish to specify a language specifically, you can change your <pre> tag slightly. Let's say we want to do html. Then we would use: <pre class="prettyprint lang-html"> instead of just <pre class="prettyprint">. So what languages can we do? Hmmm... I'm not sure, but I know we can at least do: "bsh", "c", "cc", "cpp", "cs", "csh", "cyc", "cv", "htm", "html", "java", "js", "m", "mxml", "perl", "pl", "pm", "py", "rb", "sh", "xhtml", "xml", "xsl" and probably more? Not to shaby!

Also, if you want to do html. Make sure you use "&lt;" and "&gt;" to represent "<" and ">" or your tags may not appear.

More? Yes, if you wish to edit what colors are used. Try editing prettify.css.
0 Responses