douquqiang1513 2015-01-15 03:37
浏览 86
已采纳

为什么要包含一个数据数组,从控制器调用render()?

I'm trying to understand how Yii passes data from page to page. One thing that confused me was that the view pages associated with their respective controller could access the data sent to it through render without a post or get request. I.e.

//in the controller php file
$this->render('view',array('data1'=>$data1))) 

//in the view php file
if (isset($data1)) { //do something amazing }

Now I realize it's because the view will have access to the members of the controller. But then, if that's the case, why would anyone bother putting a data array in the render function?

Consider another example provided on SO here.

What am I misunderstanding?

  • 写回答

1条回答 默认 最新

  • doufen5175 2015-01-15 04:43
    关注

    The point of the data array parameter is to be able to pass variables to the view file that are not properties of the controller. If your controller code is, say, this:

    /* controller */
    
    $this->property = 'Controller Property';
    $variable = 'Method-scoped variable';
    
    $this->render( 'view' ); // no second parameter
    

    Then $variable would not be available in your view code:

    /* view */
    
    echo $this->property; // "Controller Property"
    echo $variable; // null;
    

    By passing an array to the render method, you can have it extract the array members into variables available in the view script:

    /* controller */
    //...
    
    $this->render( 'view', array( 'myvar' => $variable ) );
    
    /* view */
    
    echo $myvar; // "Method-scoped variable"
    

    Unless your views are only going to use controller properties in the render, you're going to need to use the second parameter to pass on scoped information so it's available to the view script.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?