Passing view file data in to partials

Let’s say I pass $model from my controller in to a view file. Within in that view file I include a partial file using renderPartial() like this:


<?php echo $this->renderPartial('_form', array('model'=>$model)); ?>

How come I have to pass $model to the partial file?

In normal PHP you would normally use an include() statement and the included file automatically has access to its parent files variables. For example:


<?php include("_form.php"); ?>

Works.

1 Like

you must pass $form too…




<?php echo $this->renderPartial('_subform', array('form' => $form, 'model'=>$model)); ?>



What’s “normal” PHP for you? Yii deals with classes and methods. renderPartial() is CController’s method and it calls include() function, but it can’t see variables of other renderPartial() methods, because all of them are local.

The actual implementatio of the render require that all variable are passed view by view.

You can also access to the controller with $this, so if you want to share some variable withoout passing all time, you can use a property of the controller.

in controller:




public $var;



in all views:




$this-var



This is how is implemented breadcrumbs and menu, there are some property in the master class Controller that you can find in /compoment

Main problem is in your understanding… renderPartial() does not the same as include…

include just includes a file that is executed as part of the script that includes it… but renderPartial() renders a view… ie. it processes that view…