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 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)