2013-03-06 62 views
0

这是另一个这样的工具,其中每个博客导师假设我们都知道它是什么,因此他们从不费解释它实际上做了什么。他们继续在他们的例子中使用它,相信我们都知道发生了什么。Zend Framework中render()是做什么的

从人们如何使用或引用render(),它会建议它显示内容(例如:查看内容),但如果是这样,那么为什么我们使用echo实际显示它的内容?

其他用途表明它格式化内容,正如我们在内部使用sprintf()向表单注入变量的形式装饰器中使用的那样。

那么render()Zend_View,Zend_Layout等情况下会做什么?有人可以请他解释一下基础层面的工作情况(底层)。谢谢。

回答

3

它加载一个视图脚本并将其输出为一个字符串。

简化了一下,Zend_View取视图脚本文件(如index.phtml),并且包括在内部,以产生HTML输出。通过使用render()方法,可以采用额外的视图脚本(如可能是nav.phtml)并将其输出到父视图脚本中。这个想法是渲染在多个页面上重复的元素,而不是一次又一次地重复相同的HTML。

用于渲染方法的代码可以在Zend_View_Abstract类中找到,它是下列:

/** 
* Processes a view script and returns the output. 
* 
* @param string $name The script name to process. 
* @return string The script output. 
*/ 
public function render($name) 
{ 
    // find the script file name using the parent private method 
    $this->_file = $this->_script($name); 
    unset($name); // remove $name from local scope 

    ob_start(); 
    $this->_run($this->_file); 

    return $this->_filter(ob_get_clean()); // filter output 
} 

_run()方法的实现可以在类Zend_View中找到,如下:

/** 
* Includes the view script in a scope with only public $this variables. 
* 
* @param string The view script to execute. 
*/ 
protected function _run() 
{ 
    if ($this->_useViewStream && $this->useStreamWrapper()) { 
     include 'zend.view://' . func_get_arg(0); 
    } else { 
     include func_get_arg(0); 
    } 
} 

正如您所见,render()需要一个视图脚本名称,解析其文件名,启动输出缓冲,包含视图脚本文件(这是什么_run()方法在内部),然后通过可选过滤器传递输出,最后返回生成的字符串。

整洁的事情是,它保留了它被调用的视图对象的属性(变量)(因为它是相同的Zend_View对象,只是加载了不同的视图脚本)。在这方面,它不同于partial()方法,该方法有其自己的变量范围,您可以将变量传递给它(对于渲染更小的元素(例如,当您在数据集上使用foreach时),这是非常有用的。

相关问题