14.3. 视图脚本
一旦你的Controller已经完成了变量赋值和调用了render()方法,Zend_View就会包含相应的视图脚本并在Zend_View的实例内部执行该视图脚本。因此,在你的视图脚本内,$this是指向Zend_View的实例的。
在控制器中赋值给视图的变量将作为Zend_View实例的属性,如果控制器赋值给视图一个变量"something" ,那么视图代码中就可以用$this->something来引用变量"something"。这样的作法可以让你分清哪些是来自Zend_View实例的变量,哪些是视图自身的变量。
为了说明,这里有一个例子:
<?php if ($this->books): ?>
<!-- A table of some books. -->
<table>
<tr>
<th>Author</th>
<th>Title</th>
</tr>
<?php foreach ($this->books as $key => $val): ?>
<tr>
<td><?php echo $this->escape($val['author']) ?></td>
<td><?php echo $this->escape($val['title']) ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?>
<p>There are no books to display.</p>
<?php endif; ?>
View脚本的最重要的工作之一是保证输出的内容是合适的,比如需要避免跨站攻击漏洞。除非你使用一个函数,类方法或协助器(helper)来过滤内容,你需要在输出时对变量进行过滤。
Zend_View带有一个escape()方法来提供这个功能:
<?php
// bad view-script practice:
echo $this->variable;
// good view-script practice:
echo $this->escape($this->variable);
?>
默认地,escape()方法使用PHP函数htmlspecialchars()来过滤。你可以通过setEscape()方法来在Controller内告诉Zend_View需要怎么过滤。
<?php
// create a Zend_View instance
$view = new Zend_View();
// tell it to use htmlentities as the escaping callback
$view->setEscape('htmlentities');
// or tell it to use a static class method as the callback
$view->setEscape(array('SomeClass', 'methodName'));
// or even an instance method
$obj = new SomeClass();
$view->setEscape(array($obj, 'methodName'));
// and then render your view
echo $view->render(...);
?>
设定的过滤函数会将需要过滤的变量作为其第一个参数,其它参数是可选的。
许多开发者觉得尽管PHP本身就是一个强大的模板系统,但对模板设计师来说,使用PHP标签过于复杂。所以,View脚本可能要被用来初始化和操作一个其它模板对象的实例,例如PHPLIB风格的模板。这时View脚本可能是这样的:
<?php
include_once 'template.inc';
$tpl = new Template();
if ($this->books) {
$tpl->setFile(array(
"booklist" => "booklist.tpl",
"eachbook" => "eachbook.tpl",
));
foreach ($this->books as $key => $val) {
$tpl->set_var('author', $this->escape($val['author']);
$tpl->set_var('title', $this->escape($val['title']);
$tpl->parse("books", "eachbook", true);
}
$tpl->pparse("output", "booklist");
} else {
$tpl->setFile("nobooks", "nobooks.tpl")
$tpl->pparse("output", "nobooks");
}
?>
下面是相关的模板文件:
<!-- booklist.tpl -->
<table>
<tr>
<th>Author</th>
<th>Title</th>
</tr>
{books}
</table>
<!-- eachbook.tpl -->
<tr>
<td>{author}</td>
<td>{title}</td>
</tr>
<!-- nobooks.tpl -->
<p>There are no books to display.</p>