Skip to content

Commit

Permalink
ViewBlock able to prepend with capturing mode
Browse files Browse the repository at this point in the history
  • Loading branch information
lazybobcat committed Jul 26, 2015
1 parent daf49f9 commit 8129d0a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 12 deletions.
7 changes: 1 addition & 6 deletions src/View/View.php
Expand Up @@ -590,12 +590,7 @@ public function start($name)
*/
public function append($name, $value = null)
{
if ($value !== null) {
$this->Blocks->concat($name, $value);
return;
}
$this->Blocks->start($name);
echo $this->Blocks->get($name);
$this->Blocks->concat($name, $value);
}

/**
Expand Down
32 changes: 26 additions & 6 deletions src/View/ViewBlock.php
Expand Up @@ -26,6 +26,13 @@
class ViewBlock
{

/**
* Override content
*
* @var string
*/
const OVERRIDE = 'override';

/**
* Append content
*
Expand Down Expand Up @@ -72,15 +79,18 @@ class ViewBlock
* using View::get();
*
* @param string $name The name of the block to capture for.
* @param string $mode If ViewBlock::OVERRIDE existing content will be overridden by new content.
* If ViewBlock::APPEND content will be appended to existing content.
* If ViewBlock::PREPEND it will be prepended.
* @throws \Cake\Core\Exception\Exception When starting a block twice
* @return void
*/
public function start($name)
public function start($name, $mode = ViewBlock::OVERRIDE)
{
if (in_array($name, $this->_active)) {
if (in_array($name, array_keys($this->_active))) {
throw new Exception(sprintf("A view block with the name '%s' is already/still open.", $name));
}
$this->_active[] = $name;
$this->_active[$name] = $mode;
ob_start();
}

Expand All @@ -98,9 +108,14 @@ public function end()
return;
}
if (!empty($this->_active)) {
$active = end($this->_active);
$mode = end($this->_active);
$active = key($this->_active);
$content = ob_get_clean();
$this->_blocks[$active] = $content;
if($mode === ViewBlock::OVERRIDE) {
$this->_blocks[$active] = $content;
} else {
$this->concat($active, $content, $mode);
}
array_pop($this->_active);
}
}
Expand All @@ -119,8 +134,13 @@ public function end()
* If ViewBlock::PREPEND it will be prepended.
* @return void
*/
public function concat($name, $value, $mode = ViewBlock::APPEND)
public function concat($name, $value = null, $mode = ViewBlock::APPEND)
{
if($value === null) {
$this->start($name, $mode);
return;
}

if (!isset($this->_blocks[$name])) {
$this->_blocks[$name] = '';
}
Expand Down

0 comments on commit 8129d0a

Please sign in to comment.