Getting the block names of a Twig template

Published on 2020-08-08 • Modified on 2020-08-08

In this snippet, we will see how to get the block names of a Twig template. To do so, we must use the Twig\Environment service which is available in the service container. Sorry, I didn't find a doc on the subject but the GitHub PR when this function was modified.


<?php declare(strict_types=1);

// src/Controller/Snippet/Snippet108Trait.php

namespace App\Controller\Snippet;

use Twig\Environment;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 *
 * @property Environment $twigEnvironment
 */
trait Snippet108Trait
{
    public function snippet108(): void
    {
        $blockNames = $this->twigEnvironment->load('layout.html.twig')->getBlockNames();
        var_dump($blockNames);

        // That's it! 😁
    }
}

 Run this snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫   Read the doc  Random snippet

<?php declare(strict_types=1);

namespace App\Tests\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Twig\Environment;

/**
 * @covers Snippet108Trait
 */
final class Snippet108Test extends KernelTestCase
{
    private Environment $twigEnvironment;

    protected function setUp(): void
    {
        self::bootKernel();
        $this->twigEnvironment = self::$container->get(Environment::class);
    }

    /**
     * @covers Snippet108Trait::snippet108
     */
    public function testSnippet108(): void
    {
        $blockNames = $this->twigEnvironment->load('layout.html.twig')->getBlockNames();
        self::assertCount(14, $blockNames);
    }
}