Click here to Skip to main content
Click here to Skip to main content

Send content to the layout using a Helper on CakePHP

By , 12 Apr 2013
 

This post is based on Robert Conner's code forCakePHP 1.x., and I made some changes to get it to work onCakePHP 2.x. The original post can be found here.

Maybe some people have faced problems trying to send some content to the layout on CakePHP. By content I mean not only a simple string but a whole a piece of HTML code. To solve this, we can create a Helper on CakePHP 2.x, according to the following steps:

1. Create the Helper

On theViews/Helpers folder, you need to create the .php file for the helper. In this case we will call it LayoutHelper.php.

class LayoutHelper extends AppHelper {
 var $__blockName = null;
 function blockStart($name) {
  if (empty($name))
   trigger_error('LayoutHelper::blockStart - name is a required parameter');
  if (!is_null($this->__blockName))
   trigger_error('LayoutHelper::blockStart - Blocks cannot overlap');
  
  $this->__blockName = $name;
  ob_start();
  return null;
 }
 
 function blockEnd(&$view){
  $buffer = @ob_get_contents();
  @ob_end_clean();
  $out = $buffer
  $view->viewVars[$this->__blockName . '_for_layout'] = $out;
  $this->__blockName = null
 }

 function output($var) {
  if (isset($var) && $var != null)
  echo $var;
 }
}

2. Setting up the content

For setting up the content that we want to send to the layout, we use the Helper.

$layout = $this->Helpers->load('Layout');
$layout->blockStart('custom_content');

Right after this, we specify the content that will be sent to the layout:

<div>Custom content</div>

and we close the block:

$layout->blockEnd($this);

3. Show the content

For showing the content on the layout, we add the following:

$layout = $this->Helpers->load('Layout');
$layout->output($custom_content_for_layout);

As we can see, this is really simple and also very useful when trying to customize the content on the layout according to the view we are loading.

I wrote this article also on The Bakery

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

pollirrata
Software Developer e-nnovare
Mexico Mexico
Member
Jorge is an enthusiast web developer who love to learn something new every day.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130513.1 | Last Updated 12 Apr 2013
Article Copyright 2013 by pollirrata
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid