Skip to content
m3nt0r edited this page Jun 25, 2012 · 1 revision

I've added some utitlity methods so i can bring in any Helper (and associated Extensions/Filters) as quickly as possible.

If you want to contribute some filters i suggest to look inside the extensions directory and copy one of the existing files and simply rename methods and class names to your needs.

You are not limited to filters, by the way. Read the Twig Documentation about extending. The way i extend Filters can also be used to add TokenParsers, Functions, Operators, Globals and more.

Writing your Extension

Extend TwigView_Extension for your method collection. There is not much code in it, but we are at an early stage and inheriting is always a good idea when extending a package.

class My_TwigView_Extension extends TwigView_Extension {
    static function something() {
        // do something
    }
}

You can then use any helper like this:

self::helperObject('YourHelper')->something()
self::helperObject('HtmlHelper')->css('my-style') // for example

The first time you do this the YourHelper object is stored in the ClassRegistry for future reference.

Connect with Twig

This part tells Twig what the extension is about. I recommend reading the Twig documentation to get a better picture of what is possible. Here an example that i used in all of my extensions, providing new filter keywords and point them to my static wrapper method.

class My_Twig_Extension extends Twig_Extension {
    public function getName() {
        return 'MyExtension';
    }
    public function getFilters() {
        return array(
            'something' => new Twig_Filter_Function('My_TwigView_Extension::something'),
        );
    }
}

Registering your Extension

You should now have two classes in your extension file.

  • My_TwigView_Extension (the one interacting with cakephp, view or containing complete custom code)
  • My_Twig_Extension (the actual twig extension)

Once you are done writing your wrapper you need to add a call to TwigView::registerExtension() somewhere in your extension file so that it is executed upon inclusion:

TwigView::registerExtension(__FILE__, 'My_Twig_Extension');

This will tell TwigView what class to use when calling TwigEnvironment::addExtension() inside the loading processing.

Loading your Extension

Save your file containing (or referencing) your extension classes in ./extensions and add the filename to the TwigView.extensions array.

Configure::write('TwigView.extensions', array(
    'time',
    'number',
    'text',
    'i18n',
    'my_extension'
));

Nice, and works?

Send me a pull request

Clone this wiki locally