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.

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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵