Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h1>Access function / logic from twig and a controller</h1> <p>I think there are two solutions for this, both should use the <code>Twig_Function_Method</code> class.</p> <h2>1</h2> <p>The first solution <code>gilden</code> already posted, is to encapsulate the logic into a service and make a wrapper for the Twig Extension.</p> <h2>2</h2> <p>Another solution is to use only the Twig Extension. The Twig Extensino is already a service, you have to define it as service with the special <code>&lt;tag name="twig.extension" /&gt;</code>. But it's also a service, which instance you can grab by the service container. And it's also possible to inject other services:</p> <p>So you have your Twig Extension / Service:</p> <pre><code>class MyTwigExtension extends \Twig_Extension { private $anotherService; public function __construct(SecurityService $anotherService= null) { $this-&gt;anotherService = $anotherService; } public function foo($param) { // do something $this-&gt;anotherService-&gt;bar($param); } public function getFunctions() { // function names in twig =&gt; function name in this calss return array( 'foo' =&gt; new \Twig_Function_Method($this, 'foo'), ); } /** * Returns the name of the extension. * * @return string The extension name */ public function getName() { return 'my_extension'; } } </code></pre> <p>The services.xml looks like this</p> <pre><code>&lt;service id="acme.my_extension" class="Acme\CoreBundle\Twig\Extension\MyTwigExtension"&gt; &lt;tag name="twig.extension" /&gt; &lt;argument type="service" id="another.service"&gt;&lt;/argument&gt; &lt;/service&gt; </code></pre> <p>To acccess to the service from your controller you only have to use this:<br> <code>$this-&gt;container-&gt;get('acme.my_extension')</code></p> <p><strong>Notice</strong> The only difference to a normal service is, that the twig extension is not lazy loaded (<a href="http://symfony.com/doc/current/cookbook/templating/twig_extension.html#register-an-extension-as-a-service">http://symfony.com/doc/current/cookbook/templating/twig_extension.html#register-an-extension-as-a-service</a>) </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload