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
This commit is contained in:
fabien
2009-12-14 06:56:48 +00:00
parent 1a033bab6f
commit 40ad5abe35
+46
View File
@@ -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());