CakePHP Geshi helper

26/04/2008 Written by: Chris

I have written a small Geshi helper for CakePHP, with Geshi you can display formatted code with colours. Just drop Geshi in your vendors directory and create a a helper to your taste.. personally I use a style helper which contains different methods to help format an article.

Now just create <pre class="php"> code goes here </pre> in your article and your done. Replace php with the language of your choice.

  1. <?php
  2. class StyleHelper extends AppHelper {
  3.    
  4.     /**
  5.      * This method Formats pieces of code with code coloring
  6.      *
  7.      * @access public
  8.      * @param string $content
  9.      * @return string
  10.      */
  11.         public function formatCode($content) {         
  12.                 App::import('Vendor','Geshi');
  13.                 $this->geshi = new GeSHi('', '');
  14.                 $this->geshi->set_header_type(GESHI_HEADER_DIV);
  15.                 // Turn on fancy lines
  16.                 $this->geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS, 2);        
  17.                 // Enable css class names
  18.                 $this->geshi->enable_classes();
  19.                
  20.                 return preg_replace_callback("#
  21. <pre class=\"([^\"]*)\">(.*?)</pre>
  22. #s", array(&$this, 'replaceCallback'), $content);
  23.         }
  24.        
  25.         /**
  26.          * Method to return the formatted code by Geshi
  27.          *
  28.          * @access private
  29.          * @param string $matches
  30.          * @return string
  31.          */
  32.         private function replaceCallback($matches) {
  33.                 $this->geshi->set_source(str_replace('', '', $matches[2]));
  34.                 $this->geshi->set_language($matches[1]);
  35.                 return $this->geshi->parse_code();
  36.         }    
  37. }

I have this function in a helper called style, but you can name it anything you like. To use it you can just load enter your content in the view and the formatted code will be returned.

  1. <?php
  2. echo $style->formatCode($article['Article']['article']);
  3. ?>

Related tags