Browse Source

Merge pull request #7222 from cakephp/view-layout

Allow overriding layout passed as argument by setting View::$layout in template
Mark Story 10 years ago
parent
commit
e06037a701
2 changed files with 31 additions and 4 deletions
  1. 10 4
      src/View/View.php
  2. 21 0
      tests/TestCase/View/ViewTest.php

+ 10 - 4
src/View/View.php

@@ -555,6 +555,11 @@ class View implements EventDispatcherInterface
             return;
         }
 
+        if ($layout !== null) {
+            $defaultLayout = $this->layout;
+            $this->layout = $layout;
+        }
+
         if ($view !== false && $viewFileName = $this->_getViewFileName($view)) {
             $this->_currentType = static::TYPE_VIEW;
             $this->dispatchEvent('View.beforeRender', [$viewFileName]);
@@ -562,12 +567,13 @@ class View implements EventDispatcherInterface
             $this->dispatchEvent('View.afterRender', [$viewFileName]);
         }
 
-        if ($layout === null) {
-            $layout = $this->layout;
+        if ($this->layout && $this->autoLayout) {
+            $this->Blocks->set('content', $this->renderLayout('', $this->layout));
         }
-        if ($layout && $this->autoLayout) {
-            $this->Blocks->set('content', $this->renderLayout('', $layout));
+        if ($layout !== null) {
+            $this->layout = $defaultLayout;
         }
+
         $this->hasRendered = true;
         return $this->Blocks->get('content');
     }

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

@@ -1291,6 +1291,27 @@ class ViewTest extends TestCase
     }
 
     /**
+     * Test that layout set from view file takes precedence over layout set
+     * as argument to render().
+     *
+     * @return void
+     */
+    public function testRenderUsingLayoutArgument()
+    {
+        $error = new \PDOException();
+        $error->queryString = 'this is sql string';
+        $message = 'it works';
+
+        $View = $this->PostsController->createView('Cake\Test\TestCase\View\TestView');
+        $View->set(compact('error', 'message'));
+        $View->viewPath = 'Error';
+
+        $result = $View->render('pdo_error', 'error');
+        $this->assertRegExp('/this is sql string/', $result);
+        $this->assertRegExp('/it works/', $result);
+    }
+
+    /**
      * Test render()ing a file in a subdir from a custom viewPath
      * in a plugin.
      *