Občas je třeba symfony trochu přiohnout a dostat až do twigu funkce z repository.
Pomocí služby a twig-extension by to neměl být ale problém...
Twig Extension "FooExtension.php"
namespace FooBundle\Twig;
use FooBundle\Entity\FooEntity;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Twig_Extension;
use Twig_SimpleFunction;
class fooExtension extends Twig_Extension
{
protected $doctrine;
public function __construct(RegistryInterface $doctrine) {
$this->doctrine = $doctrine;
}
public function getFunctions()
{
return array(
new Twig_SimpleFunction('functionNameForTwig', array($this, 'awesomeFunction'), array('is_safe' => array('html'))),
);
}
public function awesomeFunction($someparam)
{
$em = $this->doctrine->getManager();
return $em->getRepository('FooBundle:FooEntity')->getSomeRepositoryFunction($someParam);
}
}
Propojení našeho twig-extension a předání přístupu k doctrine "services.yml"
services:
foobundle.twig.foo_extension:
class: FooBundle\Twig\FooExtension
arguments:
doctrine: "@doctrine"
tags:
- { name: twig.extension }
A nyní v twigu můžete z vesela používat naše functionNameForTwig
...
Lorem ipsum dolor sit amet: {{ functionNameForTwig(item.superParam) }}
...
říjen 2018