class TwigEnvironment

You are here

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.

Namespace

Drupal\Core\Template

See also

core\vendor\twig\twig\lib\Twig\Environment.php

Hierarchy

Expanded class hierarchy of TwigEnvironment

Members

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::loadTemplate public function Implements Twig_Environment::loadTemplate(). Overrides Twig_Environment::loadTemplate
TwigEnvironment::needsUpdate public function Checks if the compiled template needs an update.
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

File

core/lib/Drupal/Core/Template/TwigEnvironment.php, line 22
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.
   */
  public function __construct(\Twig_LoaderInterface $loader = NULL, $options = array(), ModuleHandlerInterface $module_handler, ThemeHandlerInterface $theme_handler) {
    // @todo Pass as arguments from the DIC.
    $this->cache_object = \Drupal::cache();

    // Set twig path namespace for themes and modules.
    $namespaces = array();
    foreach ($module_handler->getModuleList() as $name => $extension) {
      $namespaces[$name] = $extension->getPath();
    }
    foreach ($theme_handler->listInfo() as $name => $extension) {
      $namespaces[$name] = $extension->getPath();
    }

    foreach ($namespaces as $name => $path) {
      $templatesDirectory = $path . '/templates';
      if (file_exists($templatesDirectory)) {
        $loader->addPath($templatesDirectory, $name);
      }
    }

    $this->templateClasses = array();

    parent::__construct($loader, $options);
  }

  /**
   * Checks if the compiled template needs an update.
   */
  public function needsUpdate($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().
   */
  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) {
        $source = $this->loader->getSource($name);
        $compiled_source = $this->compileSource($source, $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->needsUpdate($cache_filename, $name)) {
          $this->updateCompiledTemplate($cache_filename, $name);
        }

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

    if (!$this->runtimeInitialized) {
      $this->initRuntime();
    }

    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;
  }

  /**
   * {@inheritdoc}
   */
  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] = parent::getTemplateClass($name, $index);
    }
    return $this->templateClasses[$cache_index];
  }

}