function TwigEnvironment::__construct

Same name in other branches
  1. 8.9.x core/lib/Drupal/Core/Template/TwigEnvironment.php \Drupal\Core\Template\TwigEnvironment::__construct()
  2. 10 core/lib/Drupal/Core/Template/TwigEnvironment.php \Drupal\Core\Template\TwigEnvironment::__construct()
  3. 11.x core/lib/Drupal/Core/Template/TwigEnvironment.php \Drupal\Core\Template\TwigEnvironment::__construct()

Creates a TwigEnvironment object, including its cache and storage.

Parameters

string $root: The app root.

\Drupal\Core\Cache\CacheBackendInterface $cache: The cache bin.

string $twig_extension_hash: The Twig extension hash.

\Drupal\Core\State\StateInterface $state: The state service.

\Twig\Loader\LoaderInterface $loader: The Twig loader or loader chain.

array $options: The options for the Twig environment.

File

core/lib/Drupal/Core/Template/TwigEnvironment.php, line 68

Class

TwigEnvironment
A class that defines a Twig environment for Drupal.

Namespace

Drupal\Core\Template

Code

public function __construct($root, CacheBackendInterface $cache, $twig_extension_hash, StateInterface $state, LoaderInterface $loader, array $options = []) {
    $this->state = $state;
    $this->templateClasses = [];
    $options += [
        // @todo Ensure garbage collection of expired files.
'cache' => TRUE,
        'debug' => FALSE,
        'auto_reload' => NULL,
    ];
    // Ensure autoescaping is always on.
    $options['autoescape'] = 'html';
    if ($options['cache'] === TRUE) {
        $current = $state->get(static::CACHE_PREFIX_METADATA_KEY, [
            'twig_extension_hash' => '',
        ]);
        if ($current['twig_extension_hash'] !== $twig_extension_hash || empty($current['twig_cache_prefix'])) {
            $current = [
                'twig_extension_hash' => $twig_extension_hash,
                // Generate a new prefix which invalidates any existing cached files.
'twig_cache_prefix' => uniqid(),
            ];
            $state->set(static::CACHE_PREFIX_METADATA_KEY, $current);
        }
        $this->twigCachePrefix = $current['twig_cache_prefix'];
        $options['cache'] = new TwigPhpStorageCache($cache, $this->twigCachePrefix);
    }
    $this->setLoader($loader);
    parent::__construct($this->getLoader(), $options);
    $policy = new TwigSandboxPolicy();
    $sandbox = new SandboxExtension($policy, TRUE);
    $this->addExtension($sandbox);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.