I recently implemented a pretty cool code-viewer for this site. You can see it in action here, or by suffixing any JavaScript file with ‘/view’. It works on absolutely any ‘js’ file on this domain as long as it ends in the conventional ‘js’ extension.

To achieve this I had to specify a rule to rewrite all URLs ending in ‘.js/view':

# Within the .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.+.js)/view$ /utils/codeview.php?loc=/$1
</IfModule>

Behind the scenes, all URLs that fit the schema are rewritten and the ‘codeview.php’ script is requested for each. This script grabs the contents of the JS file (passed as ‘loc’ in the query string) abd runs it through GesHi to get some neat looking syntax highlighting:

include_once('geshi/geshi.php');
 
if (!isset($_GET['loc']) || substr($_GET['loc'], -3) != '.js') {
    die('You have not specified a real JavaScript file');
}
 
$location = $_GET['loc'];
$source = file_get_contents($_SERVER['DOCUMENT_ROOT'].$location);
$geshi = new GeSHi($source, 'javascript');
 
// Further down in the <body>:
echo $geshi->parse_code();

So, from now on, if you ever want to have a quick scan through the source of any of my scripts or plugins you can just suffix the location with ‘/view’!

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!