From 3f2b7e0843fcb8637273c583310ab4262285d482 Mon Sep 17 00:00:00 2001 From: Sjoerd Langkemper Date: Wed, 24 Apr 2024 10:39:44 +0200 Subject: [PATCH] Move whitespace in front of verbatim block in Blade templates Closes #51146 If a PHP end tag `?>` is followed by a newline, that newline is not shown in the output. To counteract this, CompilesEchos detects whether an echo is followed by a newline and then doubles that newline. However, if the newline is part of a verbatim block, it is already replaced by a placeholder and CompilesEchos won't detect it correctly. This change moves the whitespace in front of the verbatim block. The whitespace remains outside of the placeholder and CompilesEchos can correctly detect it. This assumes that whitespace is not modified by Blade in a manner that it would be necessary to put whitespace in a verbatim block to change its meaning. Only the final assertion in the testNewlinesAreInsertedCorrectlyAfterEcho test actually tests for what we want. The first two are more of an introduction for the reader, to show that what we test in the last assertion really makes sense. It first tests a verbatim block, then an echo statement, and then the combination of the two, what is what we are really interested in. --- src/Illuminate/View/Compilers/BladeCompiler.php | 4 ++-- tests/View/Blade/BladeVerbatimTest.php | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/View/Compilers/BladeCompiler.php b/src/Illuminate/View/Compilers/BladeCompiler.php index a7bb59e2bc51..7911462ebf32 100644 --- a/src/Illuminate/View/Compilers/BladeCompiler.php +++ b/src/Illuminate/View/Compilers/BladeCompiler.php @@ -390,8 +390,8 @@ protected function storeUncompiledBlocks($value) */ protected function storeVerbatimBlocks($value) { - return preg_replace_callback('/(?storeRawBlock($matches[1]); + return preg_replace_callback('/(?storeRawBlock($matches[2]); }, $value); } diff --git a/tests/View/Blade/BladeVerbatimTest.php b/tests/View/Blade/BladeVerbatimTest.php index dfe3eded7fb7..a6a2adc62910 100644 --- a/tests/View/Blade/BladeVerbatimTest.php +++ b/tests/View/Blade/BladeVerbatimTest.php @@ -86,4 +86,19 @@ public function testRawBlocksDontGetMixedUpWhenSomeAreRemovedByBladeComments() $this->assertSame($expected, $this->compiler->compileString($string)); } + + public function testNewlinesAreInsertedCorrectlyAfterEcho() + { + $string = "test @verbatim\nhello world\n@endverbatim"; + $expected = "test \nhello world\n"; + $this->assertSame($expected, $this->compiler->compileString($string)); + + $string = "{{ 1 }}\nhello world\n"; + $expected = "\n\nhello world\n"; + $this->assertSame($expected, $this->compiler->compileString($string)); + + $string = "{{ 1 }}@verbatim\nhello world\n@endverbatim"; + $expected = "\n\nhello world\n"; + $this->assertSame($expected, $this->compiler->compileString($string)); + } }