3.5.3.1 Interacting with Views

3.5.3.1.1 set

set(string $var, mixed $value)
  1. set(string $var, mixed $value)

set() 方法是从你的控制器向视图传输数据的主要方法.一旦你使用了set(),变量就可以在你的视图中访问了.

<?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.

?>
  1. <?php
  2. //First you pass data from the controller:
  3. $this->set('color', 'pink');
  4. //Then, in the view, you can utilize the data:
  5. You have selected <?php echo $color; ?> icing for the cake.
  6. ?>

set()方法还可以携带一个数组作为它的第一个参数.这通常是向视图分配一组信息的快速的方法.但要注意的是,在它被分配给视图前,数组键的下划线会被替换掉, (‘underscored_key’ 将会变成‘underscoredKey’):

<?php
    
$data = array(
    'color' => 'pink',
    'type' => 'sugar',
    'base_price' => 23.95
);

//make $color, $type, and $basePrice 
//available to the view:

$this->set($data);  

?>
  1. <?php
  2. $data = array(
  3. 'color' => 'pink',
  4. 'type' => 'sugar',
  5. 'base_price' => 23.95
  6. );
  7. //make $color, $type, and $basePrice
  8. //available to the view:
  9. $this->set($data);
  10. ?>

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.

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. You can also specify an alternate view 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.