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?
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With