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.

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

报告相同问题?

悬赏问题

  • ¥50 基于TwinCAT3实现力传感器的实时读取
  • ¥20 python求解八元一次不定方程,无数解中随机输出几组即可(相关搜索:用python)
  • ¥50 libreoffice导出PPTX到PDF中的错误换行问题
  • ¥15 python实现网页视频下载
  • ¥15 如何通过深度图获得物体的完整、正确点云?
  • ¥15 有没有操作系统适用白丁的经典的书籍,如何解决?(标签-学习)
  • ¥15 Catia V5 R20 64位 安装过程中选择orbix配置创建套接字失败
  • ¥100 C51单片机设计交通灯时出现的问题
  • ¥15 R语言爬虫的时候元素和园代码不一样怎么解决呀
  • ¥15 SQL删除添加数据后序号不连续问题。