From 40ad5abe35d71ad2301625f2bace70ed22d2dcd7 Mon Sep 17 00:00:00 2001 From: fabien Date: Mon, 14 Dec 2009 06:56:48 +0000 Subject: [PATCH] added a recipe in the doc about overriding the default filters git-svn-id: http://svn.twig-project.org/trunk@177 93ef8e89-cb99-4229-a87c-7fa0fa45744b --- doc/06-Recipes.markdown | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 46 insertions(+), 0 deletions(-) diff --git a/doc/06-Recipes.markdown b/doc/06-Recipes.markdown index 07a4042..c2cdff1 100644 --- a/doc/06-Recipes.markdown +++ b/doc/06-Recipes.markdown @@ -174,3 +174,49 @@ allow communication between your templates and your application: Now, you can use the setter to inject the context whenever you create a template, and use the getter from within your custom nodes. + +Overriding default Filters +-------------------------- + +If some default core filters do not suit your needs, you can easily override +them by creating your own core extension. Of course, you don't need to copy +and paste the whole core extension code of Twig. Instead, you can just extends +it and override the filter(s) by overriding the `getFilters()` method: + + [php] + class MyCoreExtension extends Twig_Extension_Core + { + public function getFilters() + { + return array_merge( + parent::getFilters(), + array( + 'date' => array('my_date_format_filter', false) + ) + ); + } + } + + function my_date_format_filter($timestamp, $format = 'F j, Y H:i') + { + return '...'.twig_date_format_filter($timestamp, $format); + } + +Here, we override the `date` filter with a custom one. Using this new core +extension is as simple as registering the `MyCoreExtension` extension by +calling the `addExtension()` method on the environment instance: + + [php] + $twig = new Twig_Environment($loader, array('debug' => true, 'cache' => false)); + $twig->addExtension(new MyCoreExtension()); + +But I can already hear some people wondering how it can work as the Core +extension is loaded by default. That's true, but the trick is that both +extensions share the same unique identifier (`core` - defined in the +`getName()` method). By registering an extension with the same name as an +existing one, you have actually overridden the default one, even if it is +already registered: + + [php] + $twig->addExtension(new Twig_Extension_Core()); + $twig->addExtension(new MyCoreExtension()); -- 1.7.2.5