1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect1 id="zend.view.scripts">
4 <title>View Scripts</title>
7 Once your controller has assigned variables and called <methodname>render()</methodname>,
8 <classname>Zend_View</classname> then includes the requested view script and executes
9 it "inside" the scope of the <classname>Zend_View</classname> instance. Therefore,
10 in your view scripts, references to $this actually point to the
11 <classname>Zend_View</classname> instance itself.
15 Variables assigned to the view from the controller are referred
16 to as instance properties. For example, if the controller were
17 to assign a variable 'something', you would refer to it as
18 $this->something in the view script. (This allows you to keep
19 track of which values were assigned to the script, and which are
20 internal to the script itself.)
24 By way of reminder, here is the example view script from the
25 <classname>Zend_View</classname> introduction.
28 <programlisting language="php"><![CDATA[
29 <?php if ($this->books): ?>
31 <!-- A table of some books. -->
38 <?php foreach ($this->books as $key => $val): ?>
40 <td><?php echo $this->escape($val['author']) ?></td>
41 <td><?php echo $this->escape($val['title']) ?></td>
49 <p>There are no books to display.</p>
54 <sect2 id="zend.view.scripts.escaping">
55 <title>Escaping Output</title>
58 One of the most important tasks to perform in a view script
59 is to make sure that output is escaped properly; among other
60 things, this helps to avoid cross-site scripting attacks.
61 Unless you are using a function, method, or helper that does
62 escaping on its own, you should always escape variables when
67 <classname>Zend_View</classname> comes with a method called escape() that does such
71 <programlisting language="php"><![CDATA[
72 // bad view-script practice:
75 // good view-script practice:
76 echo $this->escape($this->variable);
80 By default, the escape() method uses the <acronym>PHP</acronym> htmlspecialchars()
81 function for escaping. However, depending on your environment,
82 you may wish for escaping to occur in a different way. Use the
83 setEscape() method at the controller level to tell <classname>Zend_View</classname>
84 what escaping callback to use.
87 <programlisting language="php"><![CDATA[
88 // create a Zend_View instance
89 $view = new Zend_View();
91 // tell it to use htmlentities as the escaping callback
92 $view->setEscape('htmlentities');
94 // or tell it to use a static class method as the callback
95 $view->setEscape(array('SomeClass', 'methodName'));
97 // or even an instance method
98 $obj = new SomeClass();
99 $view->setEscape(array($obj, 'methodName'));
101 // and then render your view
102 echo $view->render(...);
106 The callback function or method should take the value to be
107 escaped as its first parameter, and all other parameters should
112 <sect2 id="zend.view.scripts.templates">
113 <title>Using Alternate Template Systems</title>
116 Although <acronym>PHP</acronym> is itself a powerful template system, many developers
117 feel it is too powerful or complex for their template designers and
118 will want to use an alternate template engine. <classname>Zend_View</classname> provides
119 two mechanisms for doing so, the first through view scripts, the
120 second by implementing <classname>Zend_View_Interface</classname>.
123 <sect3 id="zend.view.scripts.templates.scripts">
124 <title>Template Systems Using View Scripts</title>
127 A view script may be used to instantiate and manipulate a
128 separate template object, such as a PHPLIB-style template. The
129 view script for that kind of activity might look something like
133 <programlisting language="php"><![CDATA[
134 include_once 'template.inc';
135 $tpl = new Template();
139 "booklist" => "booklist.tpl",
140 "eachbook" => "eachbook.tpl",
143 foreach ($this->books as $key => $val) {
144 $tpl->set_var('author', $this->escape($val['author']);
145 $tpl->set_var('title', $this->escape($val['title']);
146 $tpl->parse("books", "eachbook", true);
149 $tpl->pparse("output", "booklist");
151 $tpl->setFile("nobooks", "nobooks.tpl")
152 $tpl->pparse("output", "nobooks");
157 These would be the related template files:
160 <programlisting language="html"><![CDATA[
161 <!-- booklist.tpl -->
170 <!-- eachbook.tpl -->
177 <p>There are no books to display.</p>
181 <sect3 id="zend.view.scripts.templates.interface">
182 <title>Template Systems Using Zend_View_Interface</title>
185 Some may find it easier to simply provide a
186 <classname>Zend_View</classname>-compatible template engine.
187 <classname>Zend_View_Interface</classname> defines the minimum interface needed for
191 <programlisting language="php"><![CDATA[
193 * Return the actual template engine object
195 public function getEngine();
198 * Set the path to view scripts/templates
200 public function setScriptPath($path);
203 * Set a base path to all view resources
205 public function setBasePath($path, $prefix = 'Zend_View');
208 * Add an additional base path to view resources
210 public function addBasePath($path, $prefix = 'Zend_View');
213 * Retrieve the current script paths
215 public function getScriptPaths();
218 * Overloading methods for assigning template variables as object
221 public function __set($key, $value);
222 public function __isset($key);
223 public function __unset($key);
226 * Manual assignment of template variables, or ability to assign
227 * multiple variables en masse.
229 public function assign($spec, $value = null);
232 * Unset all assigned template variables
234 public function clearVars();
237 * Render the template named $name
239 public function render($name);
243 Using this interface, it becomes relatively easy to wrap a
244 third-party template engine as a <classname>Zend_View</classname>-compatible class.
245 As an example, the following is one potential wrapper for Smarty:
248 <programlisting language="php"><![CDATA[
249 class Zend_View_Smarty implements Zend_View_Interface
260 * @param string $tmplPath
261 * @param array $extraParams
264 public function __construct($tmplPath = null, $extraParams = array())
266 $this->_smarty = new Smarty;
268 if (null !== $tmplPath) {
269 $this->setScriptPath($tmplPath);
272 foreach ($extraParams as $key => $value) {
273 $this->_smarty->$key = $value;
278 * Return the template engine object
282 public function getEngine()
284 return $this->_smarty;
288 * Set the path to the templates
290 * @param string $path The directory to set as the path.
293 public function setScriptPath($path)
295 if (is_readable($path)) {
296 $this->_smarty->template_dir = $path;
300 throw new Exception('Invalid path provided');
304 * Retrieve the current template directory
308 public function getScriptPaths()
310 return array($this->_smarty->template_dir);
314 * Alias for setScriptPath
316 * @param string $path
317 * @param string $prefix Unused
320 public function setBasePath($path, $prefix = 'Zend_View')
322 return $this->setScriptPath($path);
326 * Alias for setScriptPath
328 * @param string $path
329 * @param string $prefix Unused
332 public function addBasePath($path, $prefix = 'Zend_View')
334 return $this->setScriptPath($path);
338 * Assign a variable to the template
340 * @param string $key The variable name.
341 * @param mixed $val The variable value.
344 public function __set($key, $val)
346 $this->_smarty->assign($key, $val);
350 * Allows testing with empty() and isset() to work
355 public function __isset($key)
357 return (null !== $this->_smarty->get_template_vars($key));
361 * Allows unset() on object properties to work
366 public function __unset($key)
368 $this->_smarty->clear_assign($key);
372 * Assign variables to the template
374 * Allows setting a specific key to the specified value, OR passing
375 * an array of key => value pairs to set en masse.
378 * @param string|array $spec The assignment strategy to use (key or
379 * array of key => value pairs)
380 * @param mixed $value (Optional) If assigning a named variable,
381 * use this as the value.
384 public function assign($spec, $value = null)
386 if (is_array($spec)) {
387 $this->_smarty->assign($spec);
391 $this->_smarty->assign($spec, $value);
395 * Clear all assigned variables
397 * Clears all variables assigned to Zend_View either via
398 * {@link assign()} or property overloading
399 * ({@link __get()}/{@link __set()}).
403 public function clearVars()
405 $this->_smarty->clear_all_assign();
409 * Processes a template and returns the output.
411 * @param string $name The template to process.
412 * @return string The output.
414 public function render($name)
416 return $this->_smarty->fetch($name);
422 In this example, you would instantiate the
423 <classname>Zend_View_Smarty</classname> class instead of
424 <classname>Zend_View</classname>, and then use it in roughly the same
425 fashion as <classname>Zend_View</classname>:
428 <programlisting language="php"><![CDATA[
429 //Example 1. In initView() of initializer.
430 $view = new Zend_View_Smarty('/path/to/templates');
432 Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
433 $viewRenderer->setView($view)
434 ->setViewBasePathSpec($view->_smarty->template_dir)
435 ->setViewScriptPathSpec(':controller/:action.:suffix')
436 ->setViewScriptPathNoControllerSpec(':action.:suffix')
437 ->setViewSuffix('tpl');
439 //Example 2. Usage in action controller remains the same...
440 class FooController extends Zend_Controller_Action
442 public function barAction()
444 $this->view->book = 'Zend PHP 5 Certification Study Guide';
445 $this->view->author = 'Davey Shafik and Ben Ramsey'
449 //Example 3. Initializing view in action controller
450 class FooController extends Zend_Controller_Action
452 public function init()
454 $this->view = new Zend_View_Smarty('/path/to/templates');
455 $viewRenderer = $this->_helper->getHelper('viewRenderer');
456 $viewRenderer->setView($this->view)
457 ->setViewBasePathSpec($view->_smarty->template_dir)
458 ->setViewScriptPathSpec(':controller/:action.:suffix')
459 ->setViewScriptPathNoControllerSpec(':action.:suffix')
460 ->setViewSuffix('tpl');