I've seen a lot of questions about how to implement a Twig extension
successfully in a Symfony 2 project but no real answers (mostly snarky
comments (: ).

It took some figuring out. So here are the key steps:

* Write your Twig extension in a bundle of your choice, let's say SillyCMSBundle
* Namespace it, and make sure to 'use' the Twig classes you need so
you can still refer to them (you could also \ them every time):

namespace Application\SillyCMSBundle\Twig\Extensions;
use \Twig_Filter_Function;
use \Twig_Environment;
use \Twig_Extension;

For this to work, WikiText.php needs to live in the
src/SillyCMSBundle/Twig/Extensions folder, assuming that
src/SillyCMSBundle is where my app's kernel looks for that bundle.

* When you write your getFilters method, make sure you namespace the
string that gives the path to the filter:

public function getFilters()
    {
        return array(
            'wiki_text' => new
Twig_Filter_Function('\Application\SillyCMSBundle\Twig\Extensions\twig_wikitext_filter',
array('is_safe' => array('html'), 'pre_escape' => 'html'))
        );
    }

Notice that the function name has a fully qualified path just like a
class in a namespace.

Now functions you write in this file, which are namespaced just like
classes in this file, can actually be found by Twig.

* Like the Symfony 2 Twig documentation says, register your extension
as a service in config.yml and tag it so that the Twig bundle knows to
look for it:

services:
    twig.extension.WikiText:
       class: Application\SillyCMSBundle\Twig\Extensions\WikiText
       tags:
           - { name: twig.extension }

If you have problems, triple-check that your namespace paths are consistent.

You can find the whole thing here:

https://github.com/boutell/SillyCMS

-- 
Tom Boutell
P'unk Avenue
215 755 1330
punkave.com
window.punkave.com

-- 
If you want to report a vulnerability issue on symfony, please send it to 
security at symfony-project.com

You received this message because you are subscribed to the Google
Groups "symfony users" group.
To post to this group, send email to symfony-users@googlegroups.com
To unsubscribe from this group, send email to
symfony-users+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/symfony-users?hl=en

Reply via email to