它加载一个视图脚本并将其作为字符串输出。
稍微简化一下,Zend_View
获取一个视图脚本文件(如 index.phtml)并在内部包含它以生成 HTML 输出。通过使用该render()
方法,可以获取一个额外的视图脚本(例如 nav.phtml)并将其输出到您的父视图脚本中。这个想法是只渲染一次在许多页面上重复的元素,而不是一遍又一遍地重复相同的 HTML。
可以在Zend_View_Abstract
类中找到 render 方法的代码,如下所示:
/**
* 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);
}
}
As you can see, render()
takes a view script name, resolves its file name, initiates output buffering, includes the view script file (this is what the _run()
method does internally), then passes the output through optional filters and finally returns the generated string.
The neat thing about it is that it retains the properties (variables) of the view object it is called from (because it's the same Zend_View
object, just with a different view script loaded). In this respect, it differs from the partial()
method, which has its own variable scope and you can pass variables into it (making it useful for rendering smaller elements, such as single rows of data when you foreach
over a dataset).