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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)