Skip to content
Permalink
Browse files

Adding include method to View library to render view partials within …

…layout-driven views. Fixes #1826
  • Loading branch information...
lonnieezell committed Mar 14, 2019
1 parent 895ae04 commit ebeb635ed3ebd9e4c583a73d29132005e1a2c259
@@ -237,7 +237,7 @@ public function render(string $view, array $options = null, $saveData = null): s
// When using layouts, the data has already been stored
// in $this->sections, and no other valid output
// is allowed in $output so we'll overwrite it.
if (! is_null($this->layout))
if (! is_null($this->layout) && empty($this->currentSection))
{
$layoutView = $this->layout;
$this->layout = null;
@@ -485,6 +485,22 @@ public function renderSection(string $sectionName)
//--------------------------------------------------------------------
/**
* Used within layout views to include additional views.
*
* @param string $view
* @param array|null $options
* @param null $saveData
*
* @return string
*/
public function include(string $view, array $options = null, $saveData = null)
{
return $this->render($view, $options, $saveData);
}
//--------------------------------------------------------------------
/**
* Returns the performance data that might have been collected
* during the execution. Used primarily in the Debug Toolbar.
@@ -295,4 +295,18 @@ public function testRenderLayoutSupportsMultipleOfSameSection()
$this->assertContains($expected, $view->render('extend_two'));
}
public function testRenderLayoutWithInclude()
{
$view = new View($this->config, $this->viewsDir, $this->loader);
$view->setVar('testString', 'Hello World');
$expected = "<p>Open</p>\n<h1>Hello World</h1>";
$content = $view->render('extend_include');
$this->assertTrue(strpos($content, '<p>Open</p>') !== false);
$this->assertTrue(strpos($content, '<h1>Hello World</h1>') !== false);
$this->assertEquals(2, substr_count($content, 'Hello World'));
}
}
@@ -0,0 +1,7 @@
<?= $this->extend('layout') ?>

<?= $this->section('content') ?>

<?= $this->include('simple') ?>

<?= $this->endSection() ?>
@@ -72,3 +72,23 @@ Rendering the view and it's layout is done exactly as any other view would be di
}

The renderer is smart enough to detect whether the view should be rendered on its own, or if it needs a layout.

***********************
Including View Partials
***********************

View partials are view files that do not extend any layout. They typically include content that can be reused from
view to view. When using view layouts you must use ``$this->include()`` to include any view partials.

::

<?= $this->extend('default') ?>

<?= $this->section('content') ?>
<h1>Hello World!</h1>

<?= $this->include('sidebar') ?>
<?= $this->endSection() ?>

When calling the include() method, you can pass it all of the same options that can when rendering a normal view, including
cache directives, etc.

0 comments on commit ebeb635

Please sign in to comment.
You can’t perform that action at this time.