Embedding GitHub Gists in XHTML
If you’ve ever shared code snippets online, you’ve probably heard of Pastie or Pastebin. What you may not have heard about is GitHub’s Gist service. Basically, take the features of existing pastebins, and add versioning, SSL, and forking. Very cool stuff.
Unfortunately, the method that is used to embed them in your pages (document.write) doesn’t work in pages that are served as real XHTML. This is a PHP function that parses your content for Gists, and then fetches them and replaces the script with the Gist’s CSS & HTML markup, avoiding the use of document.write().
<?php
/** * Replaces Gist javascript instances with their actual content, * avoiding the use of document.write(). * * @param string $source (X)HTML source * * @return string (X)HTML with embedded Gists */function embed_gists($source){ $gists_regex = '/<script[^>]+src="(http:\/\/gist.github.com\/[^"]+)"[^>]*><\/script>/i';
preg_match_all($gists_regex, $source, $gists);
for ($i = 0, $n = count($gists[0]); $i < $n; $i++) {
$embed = file_get_contents($gists[1][$i]);
if ($embed != false) {
// remove document.writes $embed = preg_replace('/document.write\(\'/i', '', $embed); $embed = preg_replace('/(*ANYCRLF)\'\)$/m', '', $embed);
// remove javascript newlines $embed = preg_replace('%(?<!/)\\\%', '', $embed);
// reverse javascript escaping $embed = stripslashes($embed);
// remove line breaks $embed = preg_replace("/[\r]/", '',$embed);
// replace the script tag $source = str_replace($gists[0][$i], $embed, $source);
}
}
return $source;}
?>
I have actually created a service that acts as a proxy and removes the document.write calls in favor of proper DOM manipulation.
The service is available for free here: http://ajax-gist.com/
I have also opened a support ticket with GitHub to try to get them to updated their embed code so we won’t need to do this: http://support.github.com/discussions/gist/186-documentwrite-needs-to-be-removed
Hope you find this useful! –Aaron