yii 中render 和renderpartial的使用

render 和renderpartial之間最大的區別就是:一個是渲染模板,一個不渲染模板。

其中render 輸出父模板的內容,將渲染的內容,嵌入父模板。

renderPartial 則不輸出父模板的內容。只對本次渲染的局部內容,進行輸出。

render函數的說明如下:

public function render($view,$data=null,$return=false)
{
    if($this->beforeRender($view))
    {
        $output=$this->renderPartial($view,$data,true);//渲染子模板
        if(($layoutFile=$this->getLayoutFile($this->layout))!==false)

   //將子模版渲染的內容放到content變量中去渲染父模板,在父模板中輸出$content
            $output=$this->renderFile($layoutFile,array('content'=>$output),true);

        $this->afterRender($view,$output);

        $output=$this->processOutput($output);

        if($return)
            return $output;
        else
            echo $output;
    }
}

 

renderpartial函數的說明如下:

public function renderPartial($view,$data=null,$return=false,$processOutput=false)
{
    if(($viewFile=$this->getViewFile($view))!==false)
    {
        $output=$this->renderFile($viewFile,$data,true);
        if($processOutput)
            $output=$this->processOutput($output);
        if($return)
            return $output;
        else
            echo $output;
    }
    else
        throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
            array('{controller}'=>get_class($this), '{view}'=>$view)));
}

 

通過觀察可知,render函數內部默認執行processOutput()函數,而renderpartial函數必須制定纔會執行。

 我們經常使用的系統,通常頭部和底部是相同的,這個時候可以使用佈局渲染,每個頁面只需要使用這個佈局,然後填上中間自己的部分,這樣的好處是在修改頭部和底部的時候,不用每個頁面都修改,只要修改相應的佈局頁面就可以了。

<div>頭部的代碼</div>

<?php  echo $content;?> //替換相應的內容

<div>底部的代碼</div>

使用的佈局的時候,只需要在使用render函數,同時設置佈局使用的文件,就可以了。

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章