A class that defines a Twig environment for Drupal.

Instances of this class are used to store the configuration and extensions, and are used to load templates from the file system or other locations.


Expanded class hierarchy of TwigEnvironment

See also


1 string reference to 'TwigEnvironment'
core.services.yml in core/core.services.yml
1 service uses TwigEnvironment


core/lib/Drupal/Core/Template/TwigEnvironment.php, line 20
Contains \Drupal\Core\Template\TwigEnvironment.


View source
class TwigEnvironment extends \Twig_Environment {
  protected $cache_object = NULL;
  protected $storage = NULL;

   * Static cache of template classes.
   * @var array
  protected $templateClasses;

   * Constructs a TwigEnvironment object and stores cache and storage
   * internally.
   * @param string $root
   *   The app root.
   * @param \Twig_LoaderInterface $loader
   *   The Twig loader or loader chain.
   * @param array $options
   *   The options for the Twig environment.
  public function __construct($root, \Twig_LoaderInterface $loader = NULL, $options = array()) {
    // @todo Pass as arguments from the DIC.
    $this->cache_object = \Drupal::cache();

    // Ensure that twig.engine is loaded, given that it is needed to render a
    // template because functions like twig_drupal_escape_filter are called.
    require_once $root . '/core/themes/engines/twig/twig.engine';

    $this->templateClasses = array();

    $options += array(
      // @todo Ensure garbage collection of expired files.
      'cache' => TRUE,
      'debug' => FALSE,
      'auto_reload' => NULL,
    // Ensure autoescaping is always on.
    $options ['autoescape'] = TRUE;

    $this->loader = $loader;
    parent::__construct($this->loader, $options);

   * Checks if the compiled template needs an update.
  protected function isFresh($cache_filename, $name) {
    $cid = 'twig:' . $cache_filename;
    $obj = $this->cache_object->get($cid);
    $mtime = isset($obj->data) ? $obj->data : FALSE;
    return $mtime === FALSE || $this->isTemplateFresh($name, $mtime);

   * Compile the source and write the compiled template to disk.
  public function updateCompiledTemplate($cache_filename, $name) {
    $source = $this->loader->getSource($name);
    $compiled_source = $this->compileSource($source, $name);
    $this->storage()->save($cache_filename, $compiled_source);
    // Save the last modification time
    $cid = 'twig:' . $cache_filename;
    $this->cache_object->set($cid, REQUEST_TIME);

   * Implements Twig_Environment::loadTemplate().
   * We need to overwrite this function to integrate with drupal_php_storage().
   * This is a straight copy from loadTemplate() changed to use
   * drupal_php_storage().
   * @param string $name
   *   The template name or the string which should be rendered as template.
   * @param int $index
   *   The index if it is an embedded template.
   * @return \Twig_TemplateInterface
   *   A template instance representing the given template name.
   * @throws \Twig_Error_Loader
   *   When the template cannot be found.
   * @throws \Twig_Error_Syntax
   *   When an error occurred during compilation.
  public function loadTemplate($name, $index = NULL) {
    $cls = $this->getTemplateClass($name, $index);

    if (isset($this->loadedTemplates [$cls])) {
      return $this->loadedTemplates [$cls];

    if (!class_exists($cls, FALSE)) {
      $cache_filename = $this->getCacheFilename($name);

      if ($cache_filename === FALSE) {
        $compiled_source = $this->compileSource($this->loader->getSource($name), $name);
        eval('?' . '>' . $compiled_source);
      else {

        // If autoreload is on, check that the template has not been
        // modified since the last compilation.
        if ($this->isAutoReload() && !$this->isFresh($cache_filename, $name)) {
          $this->updateCompiledTemplate($cache_filename, $name);

        if (!$this->storage()->load($cache_filename)) {
          $this->updateCompiledTemplate($cache_filename, $name);

    if (!$this->runtimeInitialized) {

    return $this->loadedTemplates [$cls] = new $cls($this);

   * Gets the PHP code storage object to use for the compiled Twig files.
   * @return \Drupal\Component\PhpStorage\PhpStorageInterface
  protected function storage() {
    if (!isset($this->storage)) {
      $this->storage = PhpStorageFactory::get('twig');
    return $this->storage;

   * Gets the template class associated with the given string.
   * @param string $name
   *   The name for which to calculate the template class name.
   * @param int $index
   *   The index if it is an embedded template.
   * @return string
   *   The template class name.
  public function getTemplateClass($name, $index = NULL) {
    // We override this method to add caching because it gets called multiple
    // times when the same template is used more than once. For example, a page
    // rendering 50 nodes without any node template overrides will use the same
    // node.html.twig for the output of each node and the same compiled class.
    $cache_index = $name . (NULL === $index ? '' : '_' . $index);
    if (!isset($this->templateClasses [$cache_index])) {
      $this->templateClasses [$cache_index] = $this->templateClassPrefix . hash('sha256', $this->loader->getCacheKey($name)) . (NULL === $index ? '' : '_' . $index);
    return $this->templateClasses [$cache_index];

   * Renders a twig string directly.
   * Warning: You should use the render element 'inline_template' together with
   * the #template attribute instead of this method directly.
   * On top of that you have to ensure that the template string is not dynamic
   * but just an ordinary static php string, because there may be installations
   * using read-only PHPStorage that want to generate all possible twig
   * templates as part of a build step. So it is important that an automated
   * script can find the templates and extract them. This is only possible if
   * the template is a regular string.
   * @param string $template_string
   *   The template string to render with placeholders.
   * @param array $context
   *   An array of parameters to pass to the template.
   * @return string
   *   The rendered inline template.
  public function renderInline($template_string, array $context = array()) {
    return $this->loadTemplate($template_string, NULL)->render($context);



Contains filters are case sensitive
Namesort descending Modifiers Type Description
TwigEnvironment::$cache_object protected property
TwigEnvironment::$storage protected property
TwigEnvironment::$templateClasses protected property Static cache of template classes.
TwigEnvironment::getTemplateClass public function Gets the template class associated with the given string. Overrides Twig_Environment::getTemplateClass
TwigEnvironment::isFresh protected function Checks if the compiled template needs an update.
TwigEnvironment::loadTemplate public function Implements Twig_Environment::loadTemplate(). Overrides Twig_Environment::loadTemplate
TwigEnvironment::renderInline public function Renders a twig string directly.
TwigEnvironment::storage protected function Gets the PHP code storage object to use for the compiled Twig files.
TwigEnvironment::updateCompiledTemplate public function Compile the source and write the compiled template to disk.
TwigEnvironment::__construct public function Constructs a TwigEnvironment object and stores cache and storage internally. Overrides Twig_Environment::__construct
Twig_Environment::$autoReload protected property
Twig_Environment::$baseTemplateClass protected property
Twig_Environment::$binaryOperators protected property
Twig_Environment::$cache protected property
Twig_Environment::$charset protected property
Twig_Environment::$compiler protected property
Twig_Environment::$debug protected property
Twig_Environment::$extensionInitialized protected property
Twig_Environment::$extensions protected property
Twig_Environment::$filterCallbacks protected property
Twig_Environment::$filters protected property
Twig_Environment::$functionCallbacks protected property
Twig_Environment::$functions protected property
Twig_Environment::$globals protected property
Twig_Environment::$lexer protected property
Twig_Environment::$loadedTemplates protected property
Twig_Environment::$loader protected property
Twig_Environment::$parser protected property
Twig_Environment::$parsers protected property
Twig_Environment::$runtimeInitialized protected property
Twig_Environment::$staging protected property
Twig_Environment::$strictVariables protected property
Twig_Environment::$templateClassPrefix protected property
Twig_Environment::$tests protected property
Twig_Environment::$unaryOperators protected property
Twig_Environment::$visitors protected property
Twig_Environment::addExtension public function Registers an extension.
Twig_Environment::addFilter public function Registers a Filter.
Twig_Environment::addFunction public function Registers a Function.
Twig_Environment::addGlobal public function Registers a Global.
Twig_Environment::addNodeVisitor public function Registers a Node Visitor.
Twig_Environment::addTest public function Registers a Test.
Twig_Environment::addTokenParser public function Registers a Token Parser.
Twig_Environment::clearCacheFiles public function Clears the template cache files on the filesystem.
Twig_Environment::clearTemplateCache public function Clears the internal template cache.
Twig_Environment::compile public function Compiles a node and returns the PHP code.
Twig_Environment::compileSource public function Compiles a template source code.
Twig_Environment::computeAlternatives public function
Twig_Environment::disableAutoReload public function Disables the auto_reload option.
Twig_Environment::disableDebug public function Disables debugging mode.
Twig_Environment::disableStrictVariables public function Disables the strict_variables option.
Twig_Environment::display public function Displays a template.
Twig_Environment::enableAutoReload public function Enables the auto_reload option.
Twig_Environment::enableDebug public function Enables debugging mode.
Twig_Environment::enableStrictVariables public function Enables the strict_variables option.
Twig_Environment::getBaseTemplateClass public function Gets the base template class for compiled templates.
Twig_Environment::getBinaryOperators public function Gets the registered binary Operators.
Twig_Environment::getCache public function Gets the cache directory or false if cache is disabled.
Twig_Environment::getCacheFilename public function Gets the cache filename for a given template.
Twig_Environment::getCharset public function Gets the default template charset.
Twig_Environment::getCompiler public function Gets the Compiler instance.
Twig_Environment::getExtension public function Gets an extension by name.
Twig_Environment::getExtensions public function Returns all registered extensions.
Twig_Environment::getFilter public function Get a filter by name.
Twig_Environment::getFilters public function Gets the registered Filters.
Twig_Environment::getFunction public function Get a function by name.
Twig_Environment::getFunctions public function Gets registered functions.
Twig_Environment::getGlobals public function Gets the registered Globals.
Twig_Environment::getLexer public function Gets the Lexer instance.
Twig_Environment::getLoader public function Gets the Loader instance.
Twig_Environment::getNodeVisitors public function Gets the registered Node Visitors.
Twig_Environment::getParser public function Gets the Parser instance.
Twig_Environment::getTags public function Gets registered tags.
Twig_Environment::getTemplateClassPrefix public function Gets the template class prefix.
Twig_Environment::getTest public function Gets a test by name.
Twig_Environment::getTests public function Gets the registered Tests.
Twig_Environment::getTokenParsers public function Gets the registered Token Parsers.
Twig_Environment::getUnaryOperators public function Gets the registered unary Operators.
Twig_Environment::hasExtension public function Returns true if the given extension is registered.
Twig_Environment::initExtension protected function
Twig_Environment::initExtensions protected function
Twig_Environment::initGlobals protected function
Twig_Environment::initRuntime public function Initializes the runtime environment.
Twig_Environment::isAutoReload public function Checks if the auto_reload option is enabled.
Twig_Environment::isDebug public function Checks if debug mode is enabled.
Twig_Environment::isStrictVariables public function Checks if the strict_variables option is enabled.
Twig_Environment::isTemplateFresh public function Returns true if the template is still fresh.
Twig_Environment::mergeGlobals public function Merges a context with the defined globals.
Twig_Environment::parse public function Converts a token stream to a node tree.
Twig_Environment::registerUndefinedFilterCallback public function
Twig_Environment::registerUndefinedFunctionCallback public function
Twig_Environment::removeExtension Deprecated public function Removes an extension by name.
Twig_Environment::render public function Renders a template.
Twig_Environment::resolveTemplate public function Tries to load a template consecutively from an array.
Twig_Environment::setBaseTemplateClass public function Sets the base template class for compiled templates.
Twig_Environment::setCache public function Sets the cache directory or false if cache is disabled.
Twig_Environment::setCharset public function Sets the default template charset.
Twig_Environment::setCompiler public function Sets the Compiler instance.
Twig_Environment::setExtensions public function Registers an array of extensions.
Twig_Environment::setLexer public function Sets the Lexer instance.
Twig_Environment::setLoader public function Sets the Loader instance.
Twig_Environment::setParser public function Sets the Parser instance.
Twig_Environment::tokenize public function Tokenizes a source code.
Twig_Environment::VERSION constant
Twig_Environment::writeCacheFile protected function