Yii中render和renderPartial的区别

yipeiwu_com5年前PHP代码库

以下由我们在信易网络公司开发项目的时候终结出的一些经验
在进行页面输出渲染的时候。

1.render 输出父模板的内容,将渲染的内容,嵌入父模板。|
2.renderPartial 则不输出父模板的内容。只对本次渲染的局部内容,进行输出。

同时还有个重要的区别:

render 函数内部默认执行processOutput($output)函数, 会将把组件,比如 CTreeView 里面注册到 CClientScript 里面的
需要的脚本进行渲染输出。

而renderPartial() 默认不自动渲染输出客户端脚本,需要进行参数的指定,才会输出:
renderPartial($view,$data=null,$return=false,$processOutput=false)
指定processOutput 为 true 即可。

比如要局部输出 CTreeView ,用renderPartial 进行渲染,如果按照默认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;
}

以上在实际操作中还是比较有用的,比如你不想用大组建,可以直接将变量输到模板,也可以将多个变量组成数组输到模版里面去.

相关文章

php自定义函数br2nl实现将html中br换行符转换为文本输入中换行符的方法【与函数nl2br功能相反】

本文实例讲述了php自定义函数br2nl实现将html中br换行符转换为文本输入中换行符的方法。分享给大家供大家参考,具体如下: 下面这几个方法将能够帮你解决这个问题。 PHP版将htm...

PHP使用微信开发模式实现搜索已发送图文及匹配关键字回复的方法

PHP使用微信开发模式实现搜索已发送图文及匹配关键字回复的方法

本文实例讲述了PHP使用微信开发模式实现搜索已发送图文及匹配关键字回复的方法。分享给大家供大家参考,具体如下: 用户发送关键字,搜索相应的图文进行回复。 模拟登陆就不说了 右键看“已发送...

用PHP函数解决SQL injection

SQL injection问题在ASP上可是闹得沸沸扬扬当然还有不少国内外著名的PHP程序“遇难”。至于SQL injection的详情,网上的文章太多了,在此就不...

解析:php调用MsSQL存储过程使用内置RETVAL获取过程中的return值

【PHP代码】复制代码 代码如下: $stmt = mssql_init('P__Global_Test', $conn) or die("initialize stored...

老版本PHP转义Json里的特殊字符的函数

在给一个 App 做 API,从服务器端的 MySQL 取出数据,然后生成 JSON。数据中有个字段叫 content,里面保存了文章内容,含有大量 HTML 标签,这个字段在转 jso...