Yii中render与renderPartial的核心区别
基于信易网络公司的项目开发经验总结:在进行页面输出渲染时,需明确不同渲染函数的行为差异。
1.render 输出父模板的内容,将渲染的内容,嵌入父模板。| 2.renderPartial 则不输出父模板的内容。只对本次渲染的局部内容,进行输出。
两者之间还存在一个关键的技术区别:
render函数内部默认调用processOutput($output)方法,这会将组件(例如CTreeView)向CClientScript注册的必要脚本一并渲染输出。
而renderPartial()默认情况下不会自动渲染输出客户端脚本。若需输出脚本,必须显式指定参数:renderPartial($view,$data=null,$return=false,$processOutput=false)。将processOutput设置为true即可启用脚本输出。
例如,在使用renderPartial渲染CTreeView时,若保持默认的processOutput=false,输出的内容将不包含客户端脚本,导致结果仅为普通的ul列表,缺乏树形折叠效果。主动设定processOutput=true后,CTreeView所需的所有客户端脚本均会被正常输出在列表前方。
接下来介绍几个相关的关键函数:
关于render和renderPartial的区别已在上文阐述,此处重点说明processOutput()的作用机制。
<?php
publicfunction render($view,$data=null,$return=false)
{
if($this->beforeRender($view))
{
$output=$this->renderPartial($view,$data,true);
if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
$output=$this->renderFile($layoutFile,array('content'=>$output),true);
$this->afterRender($view,$output);
$output=$this->processOutput($output);
if($return)
return $output;
else
echo $output;
}
}
publicfunction 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
thrownewCException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
array('{controller}'=>get_class($this),'{view}'=>$view)));
}
publicfunction processOutput($output)
{
Yii::app()->getClientScript()->render($output);
// if using page caching, we should delay dynamic output replacement
if($this->_dynamicOutput!==null&& $this->isCachingStackEmpty())
{
$output=$this->processDynamicOutput($output);
$this->_dynamicOutput=null;
}
if($this->_pageStates===null)
$this->_pageStates=$this->loadPageStates();
if(!empty($this->_pageStates))
$this->savePageStates($this->_pageStates,$output);
return $output;
}
上述特性在实际操作中颇具实用价值。例如,当不需要使用大型组件时,可以直接将变量传入模板,或将多个变量组成数组传递给模板进行处理。