function TwigEnvironment::compileSource

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

File

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

Class

TwigEnvironment
A class that defines a Twig environment for Drupal.

Namespace

Drupal\Core\Template

Code

public function compileSource(Source $source) {
    // Note: always use \Drupal\Core\Serialization\Yaml here instead of the
    // "serializer.yaml" service. This allows the core serializer to utilize
    // core related functionality which isn't available as the standalone
    // component based serializer.
    $frontMatter = FrontMatter::create($source->getCode(), Yaml::class);
    // Reconstruct the source if there is front matter data detected. Prepend
    // the source with {% line \d+ %} to inform Twig that the source code
    // actually starts on a different line past the front matter data. This is
    // particularly useful when used in error reporting.
    try {
        if (($line = $frontMatter->getLine()) > 1) {
            $content = "{% line {$line} %}" . $frontMatter->getContent();
            $source = new Source($content, $source->getName(), $source->getPath());
        }
    } catch (FrontMatterParseException $exception) {
        // Convert parse exception into a syntax exception for Twig and append
        // the path/name of the source to help further identify where it occurred.
        $message = sprintf($exception->getMessage() . ' in %s', $source->getPath() ?: $source->getName());
        throw new SyntaxError($message, $exception->getSourceLine(), $source, $exception);
    }
    return parent::compileSource($source);
}

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