Browse Source

swallow leading whitespace before template tags

this makes it easier to write templates without introducing, or needing
to think about, leaving leading whitespace lying arounswallow leading
whitespace before template tags

this makes it easier to write templates without introducing, or needing
to think about, leaving leading whitespace lying aroundd
AD7six 11 years ago
parent
commit
915fd953d5

+ 2 - 1
src/View/BakeView.php

@@ -92,10 +92,11 @@ class BakeView extends View {
 		];
 
 		$viewString = str_replace(array_keys($unPhp), array_values($unPhp), $viewString);
+		$viewString = preg_replace('/\n[ \t]+<% /', "\n<% ", $viewString);
 		$viewString = str_replace(array_keys($templatify), array_values($templatify), $viewString);
 		$viewString = preg_replace('/<\?=(.*)\?>\n(.)/', "<?=$1?>\n\n$2", $viewString);
 
-		$this->__viewFile = TMP . Inflector::slug(str_replace(ROOT, '', $viewFile)) . '.php';
+		$this->__viewFile = TMP . Inflector::slug(preg_replace('@.*Template[/\\\\]@', '', $viewFile)) . '.php';
 		file_put_contents($this->__viewFile, $viewString);
 
 		unset($randomString, $templatify, $viewFile, $viewString);

+ 21 - 0
tests/TestCase/View/BakeViewTest.php

@@ -99,4 +99,25 @@ class BakeViewTest extends TestCase {
 			'Tags at the end of a line should not swallow new lines when rendered'
 		);
 	}
+
+	public function testSwallowLeadingWhitespace() {
+		$result = $this->View->render('view_tests/leading-whitespace');
+		$expected = $this->_getCompareTemplate('leading-whitespace');
+
+		$this->assertSame(
+			$expected,
+			$result,
+			'Leading whitespace in bake templates should not result in leading/loose whitespace in rendered results'
+		);
+	}
+
+/**
+ * _getCompareTemplate
+ *
+ * @param string $template
+ * @return string
+ */
+	protected function _getCompareTemplate($template) {
+		return file_get_contents(dirname(dirname(__DIR__)) . "/test_app/TestApp/Template/Bake/view_tests_compare/$template.ctp");
+	}
 }

+ 13 - 0
tests/test_app/TestApp/Template/Bake/view_tests/leading-whitespace.ctp

@@ -0,0 +1,13 @@
+<% foreach([1,2,3] as $number): %>
+	<%= $number %>
+<% endforeach; %>
+
+<% foreach([1,2,3] as $number): %>
+	number
+<% endforeach; %>
+
+This should make no difference:
+			<% foreach([1,2,3] as $number): %>
+	<%= $number %>
+			<% endforeach; %>
+And the previous line should not have leading whitespace.

+ 4 - 0
tests/test_app/TestApp/Template/Bake/view_tests/newlines.ctp

@@ -0,0 +1,4 @@
+There should be a newline about here: <%= "" %>
+And this should be on the next line.
+
+There should be no new line after this<%= "" %>

+ 13 - 0
tests/test_app/TestApp/Template/Bake/view_tests_compare/leading-whitespace.ctp

@@ -0,0 +1,13 @@
+	1
+	2
+	3
+
+	number
+	number
+	number
+
+This should make no difference:
+	1
+	2
+	3
+And the previous line should not have leading whitespace.