Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Config Parameter in Twig Extension

Tags:

twig

symfony

I am creating Twig extensions so I can create custom filters and functions. I need to access a globally configured parameter in the 'parameters.ini' file.

How would I go about that?

like image 970
jbsound Avatar asked Jun 18 '12 19:06

jbsound


2 Answers

You can pass them via dependency injection. Either pass the parameters via the constructor or use setter methods. This example uses xml for service definitions:

public class MyExtension extends \Twig_Extension
{
    protected $param;

    public function __construct($param)
    {
        $this->param = $param;
    }
}

<!-- in services.xml -->
<service id="my_bundle.twig.extension.name" class="Acme\Bundle\DemoBundle\Twig\Extension\MyExtension">
    <argument>%my_parameter%</argument>
    <tag name="twig.extension" />
</service>

Notice how the parameter is confined in percentage symbols. You can read more about dependency injection from the official book.

like image 107
kgilden Avatar answered Sep 24 '22 21:09

kgilden


This is not a good practice to use container in Twig extensions but you can pass the service_container as argument when declaring your twig extension in services.xml

 <service id="example.twig.my_extension" class="Example\CoreBundle\Twig\MyExtension">
            <argument type="service" id="service_container" />
            <tag name="twig.extension" />
        </service>

add the ContainerInterface argument in the __construct() function declaration :

<?php
namespace Example\CoreBundle\Twig;

use Symfony\Component\DependencyInjection\ContainerInterface;

class MyExtension extends \Twig_Extension
{    
    /**
     * @var ContainerInterface
     */
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }
    ...

(Do not forget to use Symfony\Component\DependencyInjection\ContainerInterface)

Call your config parameters in your functions like this:

$this->container->getParameter('key');
like image 44
dmrrlc Avatar answered Sep 23 '22 21:09

dmrrlc