Ladislav Maxa Ladislav Maxa - 7 months ago 79
Twig Question

Doctrine connection in Twig extension - Symfony

According to what I've read online, it should be possible to create Doctrine connection inside Twig extensions file. I'd like to create an extension with filter that would recieve id of category and then return position of that category in the categery tree as it was established in database.

Twig extension file:



namespace MyProject\AdminBundle\Twig;

class ToolboxExtension extends \Twig_Extension
protected $em;

public function __construct($em)
$this->em = $em;

public function getFilters()
return array(
new \Twig_SimpleFilter('path', array($this, 'categoryPath'))

public function categoryPath($category_id) {
$repository = $this->$em->getRepository('MyProjectAdminBundle:Category');
$category = $repository->findOneById($category_id);
$path = $repository->getPath($category);
return implode(">", $path);
return $category;

public function getName()
return 'toolbox_extension';


Services configuration file:


class: MyProject\AdminBundle\Twig\MyExtension
- { name: twig.extension }
em: "@doctrine.orm.entity_manager"

But whenever I use this filter categoryPath, Twig crashes. So the template is loaded only until the first usage of this extension.


Try replacing $this->em-> with $this->$em->.