CakePHP comes with three “for_layout” variables: $title_for_layout, $content_for_layout, and $scripts_for_layout (since 1.2). As the names imply, those variables are used within the layout as “placeholders” for some data.

The simplest way to use your own “for_layout” variable is to set a variable in your controller or view:

$this->set('var_for_layout', 'value');

You can then use this variable in your layout with:

if (isset($var_for_layout)) {
     echo $var_for_layout;
}

The “problem” of this solution is that you need an isset() check to avoid an “undefined variable” error when the variable is not set. This check is not necessary for the built-in “for_layout” variables, and so it doesn’t look very consistent if you mix those variables with your own “for_layout” variables.

To avoid this problem I wrote a simple helper, which automatically sets an empty string if the variable is not set.

class DemoHelper extends AppHelper {
    var $value = '';

    function afterRender() {
        $view = ClassRegistry::getObject('view');
        $view->set('var_for_layout', $this->value);
    }

    function setValue($value) {
        $this->value = $value;
    }
}

This helper is then included in the $helpers array of my AppController (app/app_controller.php):

var $helpers = array('Demo');

With that I can access the helper in all my views. To set the value for the $var_for_layout variable I have to use the helper instead of $this->set():

$demo->setValue('value');

In my layout I can now simply output my “for_layout” variable:

echo $var_for_layout;