getTemplateClass example

if ($template instanceof self || $template instanceof TemplateWrapper) {
                return $template;
            }

            if ($template === $this->getTemplateName()) {
                $class = static::class;
                if (false !== $pos = strrpos($class, '___', -1)) {
                    $class = substr($class, 0, $pos);
                }
            } else {
                $class = $this->env->getTemplateClass($template);
            }

            return $this->env->loadTemplate($class$template$index);
        } catch (Error $e) {
            if (!$e->getSourceContext()) {
                $e->setSourceContext($templateName ? new Source('', $templateName) : $this->getSourceContext());
            }

            if ($e->getTemplateLine() > 0) {
                throw $e;
            }

            

  public function getTemplateClass(string $name, int $index = NULL): string {
    // 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];
  }

  /** * 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 \Drupal\Component\Render\MarkupInterface|string * The rendered inline template as a Markup object. * * @see \Drupal\Core\Template\Loader\StringLoader::exists() */
    $registry = $this->container->get('theme.registry');
    $registry->reset();
    $templates = $registry->getRuntime();

    // Get the template filename and the cache filename for     // theme_test.template_test.html.twig.     $info = $templates->get('theme_test_template_test');
    $template_filename = $info['path'] . '/' . $info['template'] . $extension;

    $environment = $this->container->get('twig');
    $cache = $environment->getCache();
    $class = $environment->getTemplateClass($template_filename);
    $cache_filename = $cache->generateKey($template_filename$class);

    // Navigate to the page and make sure the template gets cached.     $this->drupalGet('theme-test/template-test');
    $this->assertTrue(PhpStorageFactory::get('twig')->exists($cache_filename), 'Cached Twig template found.');

    // Disable the Twig cache and rebuild the service container.     $parameters = $this->container->getParameter('twig.config');
    $parameters['cache'] = FALSE;
    $this->setContainerParameter('twig.config', $parameters);
    $this->rebuildContainer();

    

    use KernelTestBehaviour;

    public function testMultipleInheritance(): void
    {
        $twig = $this->initTwig([
            new BundleFixture('Storefront', __DIR__ . '/fixtures/Storefront/'),
            new BundleFixture('TestPlugin1', __DIR__ . '/fixtures/Plugins/TestPlugin1'),
            new BundleFixture('TestPlugin2', __DIR__ . '/fixtures/Plugins/TestPlugin2'),
        ]);

        $template = $twig->loadTemplate($twig->getTemplateClass('storefront/frontend/index.html.twig'), 'storefront/frontend/index.html.twig');
        static::assertSame('innerblockplugin2innerblockplugin1innerblock', $template->render([]));
    }

    public function testInterpolatedInheritance(): void
    {
        // order storefront, TestPlugin2, TestPlugin1 is important for this test. Do not change.         $twig = $this->initTwig([
            new BundleFixture('Storefront', __DIR__ . '/fixtures/Storefront/'),
            new BundleFixture('TestPlugin2', __DIR__ . '/fixtures/Plugins/TestPlugin2'),
            new BundleFixture('TestPlugin1', __DIR__ . '/fixtures/Plugins/TestPlugin1'),
        ]);

        
static::assertEquals(\array_map(Feature::normalizeName(...)$featureFlags), \array_map(Feature::normalizeName(...)$configAfterRegistration));
    }

    public function testTwigFeatureFlag(): void
    {
        $this->setUpFixtures();
        $loader = new FilesystemLoader(__DIR__ . '/_fixture/');
        $twig = new Environment($loader[
            'cache' => false,
        ]);
        $twig->addExtension(new FeatureFlagExtension());
        $template = $twig->loadTemplate($twig->getTemplateClass('featuretest.html.twig'), 'featuretest.html.twig');
        $_SERVER['FEATURE_NEXT_101'] = '1';
        static::assertSame('FeatureIsActive', $template->render([]));
        $_SERVER['FEATURE_NEXT_101'] = '0';
        static::assertSame('FeatureIsInactive', $template->render([]));
    }

    public function testTwigFeatureFlagNotRegistered(): void
    {
        $_SERVER['APP_ENV'] = 'test';
        $_ENV['APP_ENV'] = 'test';
        KernelLifecycleManager::bootKernel(true, self::$customCacheId);

        
$expected = 'Llamas sometimes spit and wrestle with their necks. Kittens are soft and fuzzy and they sometimes say meow. Flamingos have long legs and they are usually pink. Pandas eat bamboo and they are bears. Giraffes have long necks and long tongues and they eat leaves.';
    $element_copy = $element;

    // Render it twice so that twig caching is triggered.     $this->assertEquals($expected$renderer->renderRoot($element));
    $this->assertEquals($expected$renderer->renderRoot($element_copy));

    $name = '{# inline_template_start #}' . $element['test']['#template'];
    $prefix = $environment->getTwigCachePrefix();

    $cache = $environment->getCache();
    $class = $environment->getTemplateClass($name);
    $expected = $prefix . '_inline-template_' . substr(Crypt::hashBase64($class), 0, TwigPhpStorageCache::SUFFIX_SUBSTRING_LENGTH);
    $this->assertEquals($expected$cache->generateKey($name$class));
  }

  /** * Tests that exceptions are thrown when a template is not found. */
  public function testTemplateNotFoundException() {
    /** @var \Drupal\Core\Template\TwigEnvironment $environment */
    $environment = \Drupal::service('twig');

    
public function testMultipleInheritance(): void
    {
        [$twig$templateFinder] = $this->createFinder([
            new BundleFixture('Storefront', __DIR__ . '/fixtures/Storefront/'),
            new BundleFixture('TestPlugin1', __DIR__ . '/fixtures/Plugins/TestPlugin1'),
            new BundleFixture('TestPlugin2', __DIR__ . '/fixtures/Plugins/TestPlugin2'),
        ]);

        $templatePath = $templateFinder->find('@Storefront/storefront/frontend/base.html.twig');

        $template = $twig->loadTemplate($twig->getTemplateClass($templatePath)$templatePath);

        static::assertSame('Base/TestPlugin1/TestPlugin2', $template->render([]));
    }

    public function testMultipleInheritanceIfExtendingTemplateInSamePlugin(): void
    {
        [$twig$templateFinder] = $this->createFinder([
            new BundleFixture('Storefront', __DIR__ . '/fixtures/Storefront/'),
            new BundleFixture('TestPlugin1', __DIR__ . '/fixtures/Plugins/TestPlugin1'),
            new BundleFixture('TestPlugin2', __DIR__ . '/fixtures/Plugins/TestPlugin2'),
        ]);

        

    public function load($name): TemplateWrapper
    {
        if ($name instanceof TemplateWrapper) {
            return $name;
        }

        return new TemplateWrapper($this$this->loadTemplate($this->getTemplateClass($name)$name));
    }

    /** * Loads a template internal representation. * * This method is for internal use only and should never be called * directly. * * @param string $name The template name * @param int $index The index if it is an embedded template * * @throws LoaderError When the template cannot be found * @throws RuntimeError When a previously generated cache is corrupted * @throws SyntaxError When an error occurred during compilation * * @internal */
->write("use Twig\Sandbox\SecurityError;\n")
                ->write("use Twig\Sandbox\SecurityNotAllowedTagError;\n")
                ->write("use Twig\Sandbox\SecurityNotAllowedFilterError;\n")
                ->write("use Twig\Sandbox\SecurityNotAllowedFunctionError;\n")
                ->write("use Twig\Source;\n")
                ->write("use Twig\Template;\n\n")
            ;
        }
        $compiler
            // if the template name contains */, add a blank to avoid a PHP parse error             ->write('/* '.str_replace('*/', '* /', $this->getSourceContext()->getName())." */\n")
            ->write('class '.$compiler->getEnvironment()->getTemplateClass($this->getSourceContext()->getName()$this->getAttribute('index')))
            ->raw(" extends Template\n")
            ->write("{\n")
            ->indent()
            ->write("private \$source;\n")
            ->write("private \$macros = [];\n\n")
        ;
    }

    protected function compileConstructor(Compiler $compiler)
    {
        $compiler
            
return null;
        }
    }

    private function setTwigTemplate(SeoUrlRouteConfig $config, string $template): void
    {
        $template = '{% autoescape \'' . self::ESCAPE_SLUGIFY . "' %}$template{% endautoescape %}";
        $this->twig->setLoader(new ArrayLoader(['template' => $template]));

        try {
            $this->twig->loadTemplate($this->twig->getTemplateClass('template'), 'template');
        } catch (SyntaxError $syntaxError) {
            if (!$config->getSkipInvalid()) {
                throw SeoException::invalidTemplate('Syntax error: ' . $syntaxError->getMessage());
            }
        }
    }

    private function removePrefix(string $subject, string $prefix): string
    {
        if (!$prefix || mb_strpos($subject$prefix) !== 0) {
            return $subject;
        }
Home | Imprint | This part of the site doesn't use cookies.