What probably was done by the old developers was overriding the app
variable. Until Symfony @2.7 the class was called GlobalVariables
and lives in the following namespace - Symfony\Bundle\FrameworkBundle\Templating
. As of @2.7 it's called AppVariable
and it lives in this namespace - Symfony\Bridge\Twig
. What is done behind the scenes?
That class containing the global variables is simply added as twig global variable using the method addGlobal
of Twig and for the value of app
they inject the whole class as a service that's already defined. GlobalVariables
or AppVariables
accepts the service container as an argument and defines 5 methods by default that can be used in our templates. I will show you a simple way of extending that class, so you can use it to investigate.
Create simple class that we will define as a service:
<?php
namespace AppBundle\Service;
use Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables,
Symfony\Component\DependencyInjection\ContainerInterface;
class SuperGlobalsExtended extends GlobalVariables {
/**
* @var ContainerInterface
**/
protected $container = null;
public function __construct(ContainerInterface $container) {
$this->container = $container;
parent::__construct($container);
}
}
Then register it:
services:
app.super_globals_extended:
class: AppBundle\Service\SuperGlobalsExtended
arguments:
- @service_container
And last but not least, override the app
variable of twig:
twig:
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
globals:
app: @app.super_globals_extended
Now you can define your own methods in your extended class as well as accessing the previous methods that were already here.
For symfony @2.7 is the same, just the class name is different. Here I extend the GlobalVariables
, but for @2.7 you have to extend AppVariable
.
Definition of the service for @2.7 located in TwigBundle Resources folder.
<service id="twig" class="%twig.class%">
<argument type="service" id="twig.loader" />
<argument /> <!-- Twig options -->
<call method="addGlobal">
<argument>app</argument>
<argument type="service" id="twig.app_variable" />
</call>
<configurator service="twig.configurator.environment" method="configure" />
</service>
Hope this helps.