GitHub Gist Experimentation using Joomla Plugins

Written by Peter Davies on .

Whilst creating this site I've been looking at a way of embedding Gist code snippets by just adding the Gist ID. For example <gist>4682202</gist> would load the gist using the embedded code provided by GitHub. The result would is a rather nice formatted code snippet with a few more features than standard GeSHi rendering, especially for long snippets:

Plugin Creation

Firstly we need to look at how we can make a Joomla Plugin. We start by creating a copy of an existing "content" plugin, something simple like "emailcloak". We need a content based plugin as reference as they are used to modify the content prior to display, specifically using the onContentPrepare function.

Once copied go through and rename any existing references to emailcloak to whatever the new extension will be called. In this case the Gist extension is going to be called exactly that "gist".

You will then have two files in a subfolder called "gist":

  • gist/gist.xml
  • gist/gist.php

In the the gist.php file we need to remove any superflous functions and code, and concentrate on modifying the main worker function function _gist. In here we need to construct the relevant regular expression that will extract one or more of the custom HTML tag <gist>gist id here</gist>. After seaching on Google I followed a simple Stack Overflow submitted answer allowing me to create:

 
$pattern = "/<gist>(.*?)<\/gist>/";
while (preg_match($pattern, $text, $regs, PREG_OFFSET_CAPTURE)) {
  $gist_id = (int) trim($regs[1][0]);
  $replacement = '<script src="https://gist.github.com/'.$gist_id.'.js"></script>';
  $text = substr_replace($text, $replacement, $regs[0][1], strlen($regs[0][0]));
}
 
From this we can loop through a full article and replace any occurrence of our custom HTML tag with the embedded JS-based Gist.

To make the new extension active you must first use the Joomla Admin area extension manager to "discover" the new plugin (see screenshot below). Once discovered you then need to install the plugin using the menu item at the top-left, from this moment on you should see the change immediate on any page with a gist code tag.

Joomla Admin area extension manager

Resulting Joomla Gist Plugin

So, using a basic plugin created for Joomla we can do just that. The following output is now being processed by a Joomla content plugin.

This plugin is now available through the following areas:

  1. Joomla Extension Directory
  2. GitHub Project Page


References