Details renderPartial in Yii

The function is used to display the individual pieces of content:
  1. $this->renderPartial($view, $data, $return, $processOutput);
This can cause both the controller and any view-file.

$view - string name of the view-file you want to display.
$data- array of variables to be passed in the view-file.
$return - boolean, if TRUE, then instead of displaying the result (HTML-code) will be returned and it can be assigned to a variable and display later.
$processOutput - boolean, if TRUE, then the result will be present JavaScrip, CSS and meta-tags that were attached to the controller or view-file using Yii::app()->clientScript. Applies only for AJAX-query when the page you need to run certain JS-code.

Examples of usage:
Suppose that we are at site/index, and our view-files are stored in the directory "/protected/views/site/*".
It's a convention of the file names that are used to renderPartial: the filename must begin with an underscore "_", but not necessarily.

1) 10 times to display the contents of the file "_view":
  1. for($i=1; $i<=10; $i++) {
  2. $this->renderPartial('_view', array('stage'=>$i));
  3. }
File" _view":
  1. <?php echo 'Step #'.$stage; ?><br />
Result output:
Step #1
Step #2
Step #10

2) Return the result in order to put <hr /> tags between all rows from the previous example:
  1. $buffer = array();
  2. for($i=1; $i<=10; $i++) {
  3. $buffer[] = $this->renderPartial('_view', array('stage'=>$i), TRUE);
  4. }
  5. echo implode('<hr />', $buffer);

When you click on "Remove from friends" AJAX-send a request to delete and update the block with a list of friends:
  1. <div id="friends">
  2. <?php
  3. foreach ($friends as $friend) {
  4. $this->renderPartial('_friend', array('model'=>$friend));
  5. } ?>
  6. </div>

  1. <div>
  2. <?php echo CHtml::encode($friend->name); ?><br />
  3. <?php echo CHtml::ajaxLink('Delete', array('removeFriend', 'id'=>$model->id),
  4. array('update'=>'#friends'),
  5. array('confirm'=>'Are you sure you want to delete?'));
  6. ?>
  7. </div>

  1. public function actionRemoveFriend($id) {
  2. Friends::removeFriend($id);
  3. if (Yii::app()->request->isAjaxRequest) {
  4. $friends = Friends::getFriends();
  5. foreach ($friends as $friend) {
  6. $this->renderPartial('_friend', array('model'=>$friend), false, TRUE);
  7. }
  8. Yii::app()->end();
  9. } else {
  10. $this->redirect('index');
  11. }
  12. }

If the last option in the renderPartial set to TRUE, then the contents except view-file will contain JS-code that generates CHtml :: ajaxLink

Comments (0)

Leave a comment