diff --git a/modules/system/twig/Extension.php b/modules/system/twig/Extension.php index c564854d14..372ed7903d 100644 --- a/modules/system/twig/Extension.php +++ b/modules/system/twig/Extension.php @@ -84,7 +84,9 @@ public function getFilters() */ public function getTokenParsers() { - $parsers = []; + $parsers = [ + new SpacelessTokenParser + ]; /* * Include extensions provided by plugins diff --git a/modules/system/twig/SpacelessNode.php b/modules/system/twig/SpacelessNode.php new file mode 100644 index 0000000000..939326596c --- /dev/null +++ b/modules/system/twig/SpacelessNode.php @@ -0,0 +1,38 @@ + + */ +class SpacelessNode extends Node implements NodeOutputInterface +{ + public function __construct(Node $body, int $lineno, string $tag = 'spaceless') + { + parent::__construct(['body' => $body], [], $lineno, $tag); + } + + public function compile(Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ; + if ($compiler->getEnvironment()->isDebug()) { + $compiler->write("ob_start();\n"); + } else { + $compiler->write("ob_start(function () { return ''; });\n"); + } + $compiler + ->subcompile($this->getNode('body')) + ->write("echo trim(preg_replace('/>\s+<', ob_get_clean()));\n") + ; + } +} diff --git a/modules/system/twig/SpacelessTokenParser.php b/modules/system/twig/SpacelessTokenParser.php new file mode 100644 index 0000000000..d17eab1500 --- /dev/null +++ b/modules/system/twig/SpacelessTokenParser.php @@ -0,0 +1,29 @@ +parser->getStream(); + $lineno = $token->getLine(); + + $stream->expect(/* Token::BLOCK_END_TYPE */ 3); + $body = $this->parser->subparse([$this, 'decideSpacelessEnd'], true); + $stream->expect(/* Token::BLOCK_END_TYPE */ 3); + + return new SpacelessNode($body, $lineno, $this->getTag()); + } + + public function decideSpacelessEnd(Token $token) + { + return $token->test('endspaceless'); + } + + public function getTag() + { + return 'spaceless'; + } +} diff --git a/tests/unit/system/twig/SpacelessTest.php b/tests/unit/system/twig/SpacelessTest.php new file mode 100644 index 0000000000..7f58468415 --- /dev/null +++ b/tests/unit/system/twig/SpacelessTest.php @@ -0,0 +1,25 @@ +app->make('twig.environment'); + $template = $twig->createTemplate( + '

Test

+ + {% spaceless %} +

This is a sentence.

+ +

This is another sentence.

+ {% endspaceless %}' + ); + + $this->assertEquals( + '

Test

+ +

This is a sentence.

This is another sentence.

', + $template->render() + ); + } +}