3.5.3.1 Interacting with Views
3.5.3.1.1 set
set(string $var, mixed $value)
The set() method is the main way to send data from your controller to your view. Once you've used set(), the variable can be accessed in your view.
<?php
//First you pass data from the controller:
$this->set('color', 'pink');
//Then, in the view, you can utilize the data:
?>
You have selected <?php echo $color; ?> icing for the cake.
<?php//First you pass data from the controller:$this->set('color', 'pink');//Then, in the view, you can utilize the data:?>You have selected <?php echo $color; ?> icing for the cake.
The set() method also takes an associative array as its first parameter. This can often be a quick way to assign a set of information to the view.
Array keys will be inflected before they are assigned to the view ('underscored_key' becomes 'underscoredKey', etc.):
<?php
$data = array(
'color' => 'pink',
'type' => 'sugar',
'base_price' => 23.95
);
//make $color, $type, and $basePrice
//available to the view:
$this->set($data);
?>
<?php$data = array('color' => 'pink','type' => 'sugar','base_price' => 23.95);//make $color, $type, and $basePrice//available to the view:$this->set($data);?>
3.5.3.1.2 render
render(string $action, string $layout, string $file)
The render() method is automatically called at the end of each requested controller action. This method performs all the view logic (using the data you’ve given in using the set() method), places the view inside its layout and serves it back to the end user.
The default view file used by render is determined by convention. If the search() action of the RecipesController is requested, the view file in /app/views/recipes/search.ctp will be rendered.
class RecipesController extends AppController {
...
function search() {
// Render the view in /views/recipes/search.ctp
$this->render();
}
...
} class RecipesController extends AppController {...function search() {// Render the view in /views/recipes/search.ctp$this->render();}...}
Although CakePHP will automatically call it (unless you’ve set $this->autoRender to false) after every action’s logic, you can use it to specify an alternate view file by specifying an action name in the controller using $action.
If $action starts with '/' it is assumed to be a view or element file relative to the /app/views folder. This allows direct rendering of elements, very useful in ajax calls.
// Render the element in /views/elements/ajaxreturn.ctp
$this->render('/elements/ajaxreturn');
// Render the element in /views/elements/ajaxreturn.ctp$this->render('/elements/ajaxreturn');
You can also specify an alternate view or element file using the third parameter, $file. When using $file, don't forget to utilize a few of CakePHP’s global constants (such as VIEWS).
The $layout parameter allows you to specify the layout the view is rendered in.
