This is for symfony 6 twig 3 with possible to ignore template names
<?php
use Twig\Environment;
use Twig\Node\BlockNode;
use Twig\Node\BodyNode;
use Twig\Node\ModuleNode;
use Twig\Node\Node;
use Twig\Node\TextNode;
use Twig\NodeVisitor\AbstractNodeVisitor;
class DebugCommentNodeVisitor extends AbstractNodeVisitor
{
protected function doEnterNode(Node $node, Environment $env)
{
return $node;
$excludedBlockNames = [
'sonata_type_model_autocomplete_ajax_request_parameters',
'sonata_type_model_autocomplete_dropdown_item_format',
'sonata_type_model_autocomplete_selection_format',
'batch_javascript',
];
if ($node instanceof ModuleNode) {
$templateName = $node->getTemplateName();
$extension = pathinfo($templateName, PATHINFO_EXTENSION);
$node->setNode('body', new BodyNode([
new TextNode($this->createComment('BEGIN MODULE TEMPLATE: ' . $templateName, $extension), 0),
$node->getNode('body'),
new TextNode($this->createComment('END MODULE TEMPLATE: ' . $templateName, $extension), 0),
]));
} elseif ($node instanceof BlockNode) {
$name = $node->getAttribute('name');
$sourceContext = $node->getSourceContext();
if ($sourceContext) {
$sourceContextName = $sourceContext->getName();
$extension = pathinfo($sourceContextName, PATHINFO_EXTENSION);
if (!str_contains($name, 'attributes') && !in_array($name, $excludedBlockNames)) {
$commentBegin = $this->createComment("BEGIN BLOCK TEMPLATE: $name, SOURCE CONTEXT: $sourceContextName", $extension);
$commentEnd = $this->createComment("END BLOCK TEMPLATE: $name, SOURCE CONTEXT: $sourceContextName", $extension);
$node->setNode('body', new BodyNode([
new TextNode($commentBegin, 0),
$node->getNode('body'),
new TextNode($commentEnd, 0),
]));
}
}
}
return $node;
}
protected function doLeaveNode(Node $node, Environment $env)
{
return $node;
}
public function getPriority(): int
{
return 0;
}
private function createComment(string $comment, string $extension = 'html'): string
{
return match ($extension) {
'css', 'js' => '/* ' . $comment . ' */',
default => '<!-- ' . $comment . ' -->',
};
}
}