3.5.3.1 与视图进行交互

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)

render()方法在每个控制器行为(action)结束后被自动调用。该方法(使用被set()方法传递到视图中的变量)执行所有的显示层逻辑,输出到视图模板,并回显给用户。

在没有明确指明的情况下,render方法使用按照命名规约决定采用哪个模板文件。比如RecipesController的search()被执行时,/app/views/recipes/search.ctp会被自动地作为模板进行输出。

尽管CakePHP会在每个行为(action)逻辑执行结束后自动地调用该方法(除非$this->autoRender被设置为false),你也可以通过手动指定$action的值以输出到该行为(action)对应的视图模板,还可以指定第三个参数$file的值来明确指明使用的视图模板文件。使用$file的时候请尽量利用全局路径常量(比如VIEWS)。

$layout参数允许指定显示试图的时候使用哪个页面模板(layout)。