View Helpers

In your view scripts, often it is necessary to perform certain complex functions over and over: e.g., formatting a date, generating form elements, or displaying action links. You can use helper, or plugin, classes to perform these behaviors for you.

A helper is simply a class that implements the interface Zend\View\Helper. Helper simply defines two methods, setView(), which accepts a Zend\View\Renderer instance/implementation, and getView(), used to retrieve that instance. Zend\View\PhpRenderer composes a plugin broker, allowing you to retrieve helpers, and also provides some method overloading capabilities that allow proxying method calls to helpers.

As an example, let’s say we have a helper class named My\Helper\LowerCase, which we map in our plugin broker to the name “lowercase”. We can retrieve or invoke it in one of the following ways:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// $view is a PhpRenderer instance

// Via the plugin broker:
$broker = $view->getBroker();
$helper = $broker->load('lowercase');

// Retrieve the helper instance, via the method "plugin",
// which proxies to the plugin broker:
$helper = $view->plugin('lowercase');

// If the helper does not define __invoke(), the following also retrieves it:
$helper = $view->lowercase();

// If the helper DOES define __invoke, you can call the helper
// as if it is a method:
$filtered = $view->lowercase('some value');

The last two examples demonstrate how the PhpRenderer uses method overloading to retrieve and/or invoke helpers directly, offering a convenience API for end users.

A large number of helpers are provided in the standard distribution of Zend Framework. You can also register helpers by adding them to the plugin broker, or the plugin locator the broker composes. Please refer to the plugin broker documentation for details.

Included Helpers

Zend Framework comes with an initial set of helper classes. In particular, there are helpers for creating route-based URLs and HTML lists, as well as declaring variables. Additionally, there are a rich set of helpers for providing values for, and rendering, the various HTML <head> tags, such as HeadTitle, HeadLink, and HeadScript. The currently shipped helpers include:

  • url($name, $urlParams, $routeOptions, $reuseMatchedParams): Creates a URL string based on a named route. $urlParams should be an associative array of key/value pairs used by the particular route.
  • htmlList($items, $ordered, $attribs, $escape): generates unordered and ordered lists based on the $items passed to it. If $items is a multidimensional array, a nested list will be built. If the $escape flag is TRUE (default), individual items will be escaped using the view objects registered escaping mechanisms; pass a FALSE value if you want to allow markup in your lists.

BaseUrl Helper

While most URLs generated by the framework have the base URL prepended automatically, developers will need to prepend the base URL to their own URLs in order for paths to resources to be correct.

Usage of the BaseUrl helper is very straightforward:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
/*
 * The following assume that the base URL of the page/application is "/mypage".
 */

/*
 * Prints:
 * <base href="/mypage/" />
 */
<base href="<?php echo $this->baseUrl(); ?>" />

/*
 * Prints:
 * <link rel="stylesheet" type="text/css" href="/mypage/css/base.css" />
 */
<link rel="stylesheet" type="text/css"
     href="<?php echo $this->baseUrl('css/base.css'); ?>" />

Note

For simplicity’s sake, we strip out the entry PHP file (e.g., “index.php”) from the base URL that was contained in Zend_Controller. However, in some situations this may cause a problem. If one occurs, use $this->getHelper('BaseUrl')->setBaseUrl() to set your own BaseUrl.

Cycle Helper

The Cycle helper is used to alternate a set of values.

Cycle Helper Basic Usage

To add elements to cycle just specify them in constructor or use assign(array $data) function

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php foreach ($this->books as $book):?>
  <tr style="background-color:<?php echo $this->cycle(array("#F0F0F0",
                                                            "#FFFFFF"))
                                              ->next()?>">
  <td><?php echo $this->escapeHtml($book['author']) ?></td>
</tr>
<?php endforeach;?>

// Moving in backwards order and assign function
$this->cycle()->assign(array("#F0F0F0","#FFFFFF"));
$this->cycle()->prev();
?>

The output

1
2
3
4
5
6
<tr style="background-color:'#F0F0F0'">
   <td>First</td>
</tr>
<tr style="background-color:'#FFFFFF'">
   <td>Second</td>
</tr>

Working with two or more cycles

To use two cycles you have to specify the names of cycles. Just set second parameter in cycle method. $this->cycle(array("#F0F0F0","#FFFFFF"),'cycle2'). You can also use setName($name) function.

1
2
3
4
5
6
7
8
<?php foreach ($this->books as $book):?>
  <tr style="background-color:<?php echo $this->cycle(array("#F0F0F0",
                                                            "#FFFFFF"))
                                              ->next()?>">
  <td><?php echo $this->cycle(array(1,2,3),'number')->next()?></td>
  <td><?php echo $this->escapeHtml($book['author'])?></td>
</tr>
<?php endforeach;?>

Partial Helper

The Partial view helper is used to render a specified template within its own variable scope. The primary use is for reusable template fragments with which you do not need to worry about variable name clashes. Additionally, they allow you to specify partial view scripts from specific modules.

A sibling to the Partial, the PartialLoop view helper allows you to pass iterable data, and render a partial for each item.

Note

PartialLoop Counter

The PartialLoop view helper assigns a variable to the view named partialCounter which passes the current position of the array to the view script. This provides an easy way to have alternating colors on table rows for example.

Basic Usage of Partials

Basic usage of partials is to render a template fragment in its own view scope. Consider the following partial script:

1
2
3
4
5
<?php // partial.phtml ?>
<ul>
    <li>From: <?php echo $this->escapeHtml($this->from) ?></li>
    <li>Subject: <?php echo $this->escapeHtml($this->subject) ?></li>
</ul>

You would then call it from your view script using the following:

1
2
3
<?php echo $this->partial('partial.phtml', array(
    'from' => 'Team Framework',
    'subject' => 'view partials')); ?>

Which would then render:

1
2
3
4
<ul>
    <li>From: Team Framework</li>
    <li>Subject: view partials</li>
</ul>

Note

What is a model?

A model used with the Partial view helper can be one of the following:

  • Array. If an array is passed, it should be associative, as its key/value pairs are assigned to the view with keys as view variables.
  • Object implementing toArray() method. If an object is passed an has a toArray() method, the results of toArray() will be assigned to the view object as view variables.
  • Standard object. Any other object will assign the results of object_get_vars() (essentially all public properties of the object) to the view object.

If your model is an object, you may want to have it passed as an object to the partial script, instead of serializing it to an array of variables. You can do this by setting the ‘objectKey’ property of the appropriate helper:

1
2
3
4
5
6
// Tell partial to pass objects as 'model' variable
$view->partial()->setObjectKey('model');

// Tell partial to pass objects from partialLoop as 'model' variable
// in final partial view script:
$view->partialLoop()->setObjectKey('model');

This technique is particularly useful when passing Zend_Db_Table_Rowsets to partialLoop(), as you then have full access to your row objects within the view scripts, allowing you to call methods on them (such as retrieving values from parent or dependent rows).

Using PartialLoop to Render Iterable Models

Typically, you’ll want to use partials in a loop, to render the same content fragment many times; this way you can put large blocks of repeated content or complex display logic into a single location. However this has a performance impact, as the partial helper needs to be invoked once for each iteration.

The PartialLoop view helper helps solve this issue. It allows you to pass an iterable item (array or object implementing Iterator) as the model. It then iterates over this, passing, the items to the partial script as the model. Items in the iterator may be any model the Partial view helper allows.

Let’s assume the following partial view script:

1
2
3
<?php // partialLoop.phtml ?>
    <dt><?php echo $this->key ?></dt>
    <dd><?php echo $this->value ?></dd>

And the following “model”:

1
2
3
4
5
6
$model = array(
    array('key' => 'Mammal', 'value' => 'Camel'),
    array('key' => 'Bird', 'value' => 'Penguin'),
    array('key' => 'Reptile', 'value' => 'Asp'),
    array('key' => 'Fish', 'value' => 'Flounder'),
);

In your view script, you could then invoke the PartialLoop helper:

1
2
3
<dl>
<?php echo $this->partialLoop('partialLoop.phtml', $model) ?>
</dl>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<dl>
    <dt>Mammal</dt>
    <dd>Camel</dd>

    <dt>Bird</dt>
    <dd>Penguin</dd>

    <dt>Reptile</dt>
    <dd>Asp</dd>

    <dt>Fish</dt>
    <dd>Flounder</dd>
</dl>

Rendering Partials in Other Modules

Sometime a partial will exist in a different module. If you know the name of the module, you can pass it as the second argument to either partial() or partialLoop(), moving the $model argument to third position.

For instance, if there’s a pager partial you wish to use that’s in the ‘list’ module, you could grab it as follows:

1
<?php echo $this->partial('pager.phtml', 'list', $pagerData) ?>

In this way, you can re-use partials created specifically for other modules. That said, it’s likely a better practice to put re-usable partials in shared view script paths.

Placeholder Helper

The Placeholder view helper is used to persist content between view scripts and view instances. It also offers some useful features such as aggregating content, capturing view script content for later use, and adding pre- and post-text to content (and custom separators for aggregated content).

Basic Usage of Placeholders

Basic usage of placeholders is to persist view data. Each invocation of the Placeholder helper expects a placeholder name; the helper then returns a placeholder container object that you can either manipulate or simply echo out.

1
2
3
4
5
6
<?php $this->placeholder('foo')->set("Some text for later") ?>

<?php
    echo $this->placeholder('foo');
    // outputs "Some text for later"
?>

Using Placeholders to Aggregate Content

Aggregating content via placeholders can be useful at times as well. For instance, your view script may have a variable array from which you wish to retrieve messages to display later; a later view script can then determine how those will be rendered.

The Placeholder view helper uses containers that extend ArrayObject, providing a rich featureset for manipulating arrays. In addition, it offers a variety of methods for formatting the content stored in the container:

  • setPrefix($prefix) sets text with which to prefix the content. Use getPrefix() at any time to determine what the current setting is.
  • setPostfix($prefix) sets text with which to append the content. Use getPostfix() at any time to determine what the current setting is.
  • setSeparator($prefix) sets text with which to separate aggregated content. Use getSeparator() at any time to determine what the current setting is.
  • setIndent($prefix) can be used to set an indentation value for content. If an integer is passed, that number of spaces will be used; if a string is passed, the string will be used. Use getIndent() at any time to determine what the current setting is.
1
2
<!-- first view script -->
<?php $this->placeholder('foo')->exchangeArray($this->data) ?>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<!-- later view script -->
<?php
$this->placeholder('foo')->setPrefix("<ul>\n    <li>")
                         ->setSeparator("</li><li>\n")
                         ->setIndent(4)
                         ->setPostfix("</li></ul>\n");
?>

<?php
    echo $this->placeholder('foo');
    // outputs as unordered list with pretty indentation
?>

Because the Placeholder container objects extend ArrayObject, you can also assign content to a specific key in the container easily, instead of simply pushing it into the container. Keys may be accessed either as object properties or as array keys.

1
2
3
4
5
6
7
<?php $this->placeholder('foo')->bar = $this->data ?>
<?php echo $this->placeholder('foo')->bar ?>

<?php
$foo = $this->placeholder('foo');
echo $foo['bar'];
?>

Using Placeholders to Capture Content

Occasionally you may have content for a placeholder in a view script that is easiest to template; the Placeholder view helper allows you to capture arbitrary content for later rendering using the following API.

  • captureStart($type, $key) begins capturing content.

    $type should be one of the Placeholder constants APPEND or SET. If APPEND, captured content is appended to the list of current content in the placeholder; if SET, captured content is used as the sole value of the placeholder (potentially replacing any previous content). By default, $type is APPEND.

    $key can be used to specify a specific key in the placeholder container to which you want content captured.

    captureStart() locks capturing until captureEnd() is called; you cannot nest capturing with the same placeholder container. Doing so will raise an exception.

  • captureEnd() stops capturing content, and places it in the container object according to how captureStart() was called.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<!-- Default capture: append -->
<?php $this->placeholder('foo')->captureStart();
foreach ($this->data as $datum): ?>
<div class="foo">
    <h2><?php echo $datum->title ?></h2>
    <p><?php echo $datum->content ?></p>
</div>
<?php endforeach; ?>
<?php $this->placeholder('foo')->captureEnd() ?>

<?php echo $this->placeholder('foo') ?>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<!-- Capture to key -->
<?php $this->placeholder('foo')->captureStart('SET', 'data');
foreach ($this->data as $datum): ?>
<div class="foo">
    <h2><?php echo $datum->title ?></h2>
    <p><?php echo $datum->content ?></p>
</div>
 <?php endforeach; ?>
<?php $this->placeholder('foo')->captureEnd() ?>

<?php echo $this->placeholder('foo')->data ?>

Concrete Placeholder Implementations

Zend Framework ships with a number of “concrete” placeholder implementations. These are for commonly used placeholders: doctype, page title, and various <head> elements. In all cases, calling the placeholder with no arguments returns the element itself.

Documentation for each element is covered separately, as linked below:

Doctype Helper

Valid HTML and XHTML documents should include a DOCTYPE declaration. Besides being difficult to remember, these can also affect how certain elements in your document should be rendered (for instance, CDATA escaping in <script> and <style> elements.

The Doctype helper allows you to specify one of the following types:

  • XHTML11
  • XHTML1_STRICT
  • XHTML1_TRANSITIONAL
  • XHTML1_FRAMESET
  • XHTML1_RDFA
  • XHTML_BASIC1
  • HTML4_STRICT
  • HTML4_LOOSE
  • HTML4_FRAMESET
  • HTML5

You can also specify a custom doctype as long as it is well-formed.

The Doctype helper is a concrete implementation of the Placeholder helper.

Doctype Helper Basic Usage

You may specify the doctype at any time. However, helpers that depend on the doctype for their output will recognize it only after you have set it, so the easiest approach is to specify it in your bootstrap:

1
2
$doctypeHelper = new Zend_View_Helper_Doctype();
$doctypeHelper->doctype('XHTML1_STRICT');

And then print it out on top of your layout script:

1
<?php echo $this->doctype() ?>

Retrieving the Doctype

If you need to know the doctype, you can do so by calling getDoctype() on the object, which is returned by invoking the helper.

1
$doctype = $view->doctype()->getDoctype();

Typically, you’ll simply want to know if the doctype is XHTML or not; for this, the isXhtml() method will suffice:

1
2
3
if ($view->doctype()->isXhtml()) {
    // do something differently
}

You can also check if the doctype represents an HTML5 document.

1
2
3
if ($view->doctype()->isHtml5()) {
    // do something differently
}

Choosing a Doctype to Use with the Open Graph Protocol

To implement the Open Graph Protocol, you may specify the XHTML1_RDFA doctype. This doctype allows a developer to use the Resource Description Framework within an XHTML document.

1
2
$doctypeHelper = new Zend_View_Helper_Doctype();
$doctypeHelper->doctype('XHTML1_RDFA');

The RDFa doctype allows XHTML to validate when the ‘property’ meta tag attribute is used per the Open Graph Protocol spec. Example within a view script:

1
2
3
4
5
<?php echo $this->doctype('XHTML1_RDFA'); ?>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:og="http://opengraphprotocol.org/schema/">
<head>
   <meta property="og:type" content="musician" />

In the previous example, we set the property to og:type. The og references the Open Graph namespace we specified in the html tag. The content identifies the page as being about a musician. See the Open Graph Protocol documentation for supported properties. The HeadMeta helper may be used to programmatically set these Open Graph Protocol meta tags.

Here is how you check if the doctype is set to XHTML1_RDFA:

1
2
3
4
5
6
7
<?php echo $this->doctype() ?>
<html xmlns="http://www.w3.org/1999/xhtml"
      <?php if ($view->doctype()->isRdfa()): ?>
      xmlns:og="http://opengraphprotocol.org/schema/"
      xmlns:fb="http://www.facebook.com/2008/fbml"
      <?php endif; ?>
>

HeadMeta Helper

The HTML <meta> element is used to provide meta information about your HTML document – typically keywords, document character set, caching pragmas, etc. Meta tags may be either of the ‘http-equiv’ or ‘name’ types, must contain a ‘content’ attribute, and can also have either of the ‘lang’ or ‘scheme’ modifier attributes.

The HeadMeta helper supports the following methods for setting and adding meta tags:

  • appendName($keyValue, $content, $conditionalName)
  • offsetSetName($index, $keyValue, $content, $conditionalName)
  • prependName($keyValue, $content, $conditionalName)
  • setName($keyValue, $content, $modifiers)
  • appendHttpEquiv($keyValue, $content, $conditionalHttpEquiv)
  • offsetSetHttpEquiv($index, $keyValue, $content, $conditionalHttpEquiv)
  • prependHttpEquiv($keyValue, $content, $conditionalHttpEquiv)
  • setHttpEquiv($keyValue, $content, $modifiers)
  • setCharset($charset)

The following methods are also supported with XHTML1_RDFA doctype set with the Doctype helper:

  • appendProperty($property, $content, $modifiers)
  • offsetSetProperty($index, $property, $content, $modifiers)
  • prependProperty($property, $content, $modifiers)
  • setProperty($property, $content, $modifiers)

The $keyValue item is used to define a value for the ‘name’ or ‘http-equiv’ key; $content is the value for the ‘content’ key, and $modifiers is an optional associative array that can contain keys for ‘lang’ and/or ‘scheme’.

You may also set meta tags using the headMeta() helper method, which has the following signature: headMeta($content, $keyValue, $keyType = 'name', $modifiers = array(), $placement = 'APPEND'). $keyValue is the content for the key specified in $keyType, which should be either ‘name’ or ‘http-equiv’. $keyType may also be specified as ‘property’ if the doctype has been set to XHTML1_RDFA. $placement can be ‘SET’ (overwrites all previously stored values), ‘APPEND’ (added to end of stack), or ‘PREPEND’ (added to top of stack).

HeadMeta overrides each of append(), offsetSet(), prepend(), and set() to enforce usage of the special methods as listed above. Internally, it stores each item as a stdClass token, which it later serializes using the itemToString() method. This allows you to perform checks on the items in the stack, and optionally modify these items by simply modifying the object returned.

The HeadMeta helper is a concrete implementation of the Placeholder helper.

HeadMeta Helper Basic Usage

You may specify a new meta tag at any time. Typically, you will specify client-side caching rules or SEO keywords.

For instance, if you wish to specify SEO keywords, you’d be creating a meta name tag with the name ‘keywords’ and the content the keywords you wish to associate with your page:

1
2
// setting meta keywords
$this->headMeta()->appendName('keywords', 'framework, PHP, productivity');

If you wished to set some client-side caching rules, you’d set http-equiv tags with the rules you wish to enforce:

1
2
3
4
5
// disabling client-side cache
$this->headMeta()->appendHttpEquiv('expires',
                                   'Wed, 26 Feb 1997 08:21:57 GMT')
                 ->appendHttpEquiv('pragma', 'no-cache')
                 ->appendHttpEquiv('Cache-Control', 'no-cache');

Another popular use for meta tags is setting the content type, character set, and language:

1
2
3
4
// setting content type and character set
$this->headMeta()->appendHttpEquiv('Content-Type',
                                   'text/html; charset=UTF-8')
                 ->appendHttpEquiv('Content-Language', 'en-US');

If you are serving an HTML5 document, you should provide the character set like this:

1
2
// setting character set in HTML5
$this->headMeta()->setCharset('UTF-8'); // Will look like <meta charset="UTF-8">

As a final example, an easy way to display a transitional message before a redirect is using a “meta refresh”:

1
2
3
// setting a meta refresh for 3 seconds to a new url:
$this->headMeta()->appendHttpEquiv('Refresh',
                                   '3;URL=http://www.some.org/some.html');

When you’re ready to place your meta tags in the layout, simply echo the helper:

1
<?php echo $this->headMeta() ?>

HeadMeta Usage with XHTML1_RDFA doctype

Enabling the RDFa doctype with the Doctype helper enables the use of the ‘property’ attribute (in addition to the standard ‘name’ and ‘http-equiv’) with HeadMeta. This is commonly used with the Facebook Open Graph Protocol.

For instance, you may specify an open graph page title and type as follows:

1
2
3
4
5
6
7
8
$this->doctype(Zend_View_Helper_Doctype::XHTML_RDFA);
$this->headMeta()->setProperty('og:title', 'my article title');
$this->headMeta()->setProperty('og:type', 'article');
echo $this->headMeta();

// output is:
//   <meta property="og:title" content="my article title" />
//   <meta property="og:type" content="article" />

HeadScript Helper

The HTML <script> element is used to either provide inline client-side scripting elements or link to a remote resource containing client-side scripting code. The HeadScript helper allows you to manage both.

The HeadScript helper supports the following methods for setting and adding scripts:

  • appendFile($src, $type = 'text/javascript', $attrs = array())
  • offsetSetFile($index, $src, $type = 'text/javascript', $attrs = array())
  • prependFile($src, $type = 'text/javascript', $attrs = array())
  • setFile($src, $type = 'text/javascript', $attrs = array())
  • appendScript($script, $type = 'text/javascript', $attrs = array())
  • offsetSetScript($index, $script, $type = 'text/javascript', $attrs = array())
  • prependScript($script, $type = 'text/javascript', $attrs = array())
  • setScript($script, $type = 'text/javascript', $attrs = array())

In the case of the * File() methods, $src is the remote location of the script to load; this is usually in the form of a URL or a path. For the * Script() methods, $script is the client-side scripting directives you wish to use in the element.

Note

Setting Conditional Comments

HeadScript allows you to wrap the script tag in conditional comments, which allows you to hide it from specific browsers. To add the conditional tags, pass the conditional value as part of the $attrs parameter in the method calls.

Headscript With Conditional Comments

1
2
3
4
5
6
// adding scripts
$this->headScript()->appendFile(
    '/js/prototype.js',
    'text/javascript',
    array('conditional' => 'lt IE 7')
);

Note

Preventing HTML style comments or CDATA wrapping of scripts

By default HeadScript will wrap scripts with HTML comments or it wraps scripts with XHTML cdata. This behavior can be problematic when you intend to use the script tag in an alternative way by setting the type to something other then ‘text/javascript’. To prevent such escaping, pass an noescape with a value of true as part of the $attrs parameter in the method calls.

Create an jQuery template with the headScript

1
2
3
4
5
6
7
// jquery template
$template = '<div class="book">{{:title}}</div>';
$this->headScript()->appendScript(
    $template,
    'text/x-jquery-tmpl',
    array('id='tmpl-book', 'noescape' => true)
);

HeadScript also allows capturing scripts; this can be useful if you want to create the client-side script programmatically, and then place it elsewhere. The usage for this will be showed in an example below.

Finally, you can also use the headScript() method to quickly add script elements; the signature for this is headScript($mode = 'FILE', $spec, $placement = 'APPEND'). The $mode is either ‘FILE’ or ‘SCRIPT’, depending on if you’re linking a script or defining one. $spec is either the script file to link or the script source itself. $placement should be either ‘APPEND’, ‘PREPEND’, or ‘SET’.

HeadScript overrides each of append(), offsetSet(), prepend(), and set() to enforce usage of the special methods as listed above. Internally, it stores each item as a stdClass token, which it later serializes using the itemToString() method. This allows you to perform checks on the items in the stack, and optionally modify these items by simply modifying the object returned.

The HeadScript helper is a concrete implementation of the Placeholder helper.

Note

Use InlineScript for HTML Body Scripts

HeadScript‘s sibling helper, InlineScript, should be used when you wish to include scripts inline in the HTML body. Placing scripts at the end of your document is a good practice for speeding up delivery of your page, particularly when using 3rd party analytics scripts.

Note

Arbitrary Attributes are Disabled by Default

By default, HeadScript only will render <script> attributes that are blessed by the W3C. These include ‘type’, ‘charset’, ‘defer’, ‘language’, and ‘src’. However, some javascript frameworks, notably Dojo, utilize custom attributes in order to modify behavior. To allow such attributes, you can enable them via the setAllowArbitraryAttributes() method:

1
$this->headScript()->setAllowArbitraryAttributes(true);

HeadScript Helper Basic Usage

You may specify a new script tag at any time. As noted above, these may be links to outside resource files or scripts themselves.

1
2
3
// adding scripts
$this->headScript()->appendFile('/js/prototype.js')
                   ->appendScript($onloadScript);

Order is often important with client-side scripting; you may need to ensure that libraries are loaded in a specific order due to dependencies each have; use the various append, prepend, and offsetSet directives to aid in this task:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Putting scripts in order

// place at a particular offset to ensure loaded last
$this->headScript()->offsetSetFile(100, '/js/myfuncs.js');

// use scriptaculous effects (append uses next index, 101)
$this->headScript()->appendFile('/js/scriptaculous.js');

// but always have base prototype script load first:
$this->headScript()->prependFile('/js/prototype.js');

When you’re finally ready to output all scripts in your layout script, simply echo the helper:

1
<?php echo $this->headScript() ?>

Capturing Scripts Using the HeadScript Helper

Sometimes you need to generate client-side scripts programmatically. While you could use string concatenation, heredocs, and the like, often it’s easier just to do so by creating the script and sprinkling in PHP tags. HeadScript lets you do just that, capturing it to the stack:

1
2
3
4
<?php $this->headScript()->captureStart() ?>
var action = '<?php echo $this->baseUrl ?>';
$('foo_form').action = action;
<?php $this->headScript()->captureEnd() ?>

The following assumptions are made:

  • The script will be appended to the stack. If you wish for it to replace the stack or be added to the top, you will need to pass ‘SET’ or ‘PREPEND’, respectively, as the first argument to captureStart().
  • The script MIME type is assumed to be ‘text/javascript’; if you wish to specify a different type, you will need to pass it as the second argument to captureStart().
  • If you wish to specify any additional attributes for the <script> tag, pass them in an array as the third argument to captureStart().

HeadStyle Helper

The HTML <style> element is used to include CSS stylesheets inline in the HTML <head> element.

Note

Use HeadLink to link CSS files

HeadLink should be used to create <link> elements for including external stylesheets. HeadStyle is used when you wish to define your stylesheets inline.

The HeadStyle helper supports the following methods for setting and adding stylesheet declarations:

  • appendStyle($content, $attributes = array())
  • offsetSetStyle($index, $content, $attributes = array())
  • prependStyle($content, $attributes = array())
  • setStyle($content, $attributes = array())

In all cases, $content is the actual CSS declarations. $attributes are any additional attributes you wish to provide to the style tag: lang, title, media, or dir are all permissible.

Note

Setting Conditional Comments

HeadStyle allows you to wrap the style tag in conditional comments, which allows you to hide it from specific browsers. To add the conditional tags, pass the conditional value as part of the $attributes parameter in the method calls.

Headstyle With Conditional Comments

1
2
// adding scripts
$this->headStyle()->appendStyle($styles, array('conditional' => 'lt IE 7'));

HeadStyle also allows capturing style declarations; this can be useful if you want to create the declarations programmatically, and then place them elsewhere. The usage for this will be showed in an example below.

Finally, you can also use the headStyle() method to quickly add declarations elements; the signature for this is headStyle($content$placement = 'APPEND', $attributes = array()). $placement should be either ‘APPEND’, ‘PREPEND’, or ‘SET’.

HeadStyle overrides each of append(), offsetSet(), prepend(), and set() to enforce usage of the special methods as listed above. Internally, it stores each item as a stdClass token, which it later serializes using the itemToString() method. This allows you to perform checks on the items in the stack, and optionally modify these items by simply modifying the object returned.

The HeadStyle helper is a concrete implementation of the Placeholder helper.

Note

UTF-8 encoding used by default

By default, Zend Framework uses UTF-8 as its default encoding, and, specific to this case, Zend_View does as well. Character encoding can be set differently on the view object itself using the setEncoding() method (or the the encoding instantiation parameter). However, since Zend_View_Interface does not define accessors for encoding, it’s possible that if you are using a custom view implementation with this view helper, you will not have a getEncoding() method, which is what the view helper uses internally for determining the character set in which to encode.

If you do not want to utilize UTF-8 in such a situation, you will need to implement a getEncoding() method in your custom view implementation.

HeadStyle Helper Basic Usage

You may specify a new style tag at any time:

1
2
// adding styles
$this->headStyle()->appendStyle($styles);

Order is very important with CSS; you may need to ensure that declarations are loaded in a specific order due to the order of the cascade; use the various append, prepend, and offsetSet directives to aid in this task:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Putting styles in order

// place at a particular offset:
$this->headStyle()->offsetSetStyle(100, $customStyles);

// place at end:
$this->headStyle()->appendStyle($finalStyles);

// place at beginning
$this->headStyle()->prependStyle($firstStyles);

When you’re finally ready to output all style declarations in your layout script, simply echo the helper:

1
<?php echo $this->headStyle() ?>

Capturing Style Declarations Using the HeadStyle Helper

Sometimes you need to generate CSS style declarations programmatically. While you could use string concatenation, heredocs, and the like, often it’s easier just to do so by creating the styles and sprinkling in PHP tags. HeadStyle lets you do just that, capturing it to the stack:

1
2
3
4
5
<?php $this->headStyle()->captureStart() ?>
body {
    background-color: <?php echo $this->bgColor ?>;
}
<?php $this->headStyle()->captureEnd() ?>

The following assumptions are made:

  • The style declarations will be appended to the stack. If you wish for them to replace the stack or be added to the top, you will need to pass ‘SET’ or ‘PREPEND’, respectively, as the first argument to captureStart().
  • If you wish to specify any additional attributes for the <style> tag, pass them in an array as the second argument to captureStart().

HeadTitle Helper

The HTML <title> element is used to provide a title for an HTML document. The HeadTitle helper allows you to programmatically create and store the title for later retrieval and output.

The HeadTitle helper is a concrete implementation of the Placeholder helper. It overrides the toString() method to enforce generating a <title> element, and adds a headTitle() method for quick and easy setting and aggregation of title elements. The signature for that method is headTitle($title, $setType = null); by default, the value is appended to the stack (aggregating title segments) if left at null, but you may also specify either ‘PREPEND’ (place at top of stack) or ‘SET’ (overwrite stack).

Since setting the aggregating (attach) order on each call to headTitle can be cumbersome, you can set a default attach order by calling setDefaultAttachOrder() which is applied to all headTitle() calls unless you explicitly pass a different attach order as the second parameter.

HeadTitle Helper Basic Usage

You may specify a title tag at any time. A typical usage would have you setting title segments for each level of depth in your application: site, controller, action, and potentially resource.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
 // setting the controller and action name as title segments:
$request = Zend_Controller_Front::getInstance()->getRequest();
$this->headTitle($request->getActionName())
     ->headTitle($request->getControllerName());

// setting the site in the title; possibly in the layout script:
$this->headTitle('Zend Framework');

// setting a separator string for segments:
$this->headTitle()->setSeparator(' / ');

When you’re finally ready to render the title in your layout script, simply echo the helper:

1
2
<!-- renders <action> / <controller> / Zend Framework -->
<?php echo $this->headTitle() ?>

HTML Object Helpers

The HTML <object> element is used for embedding media like Flash or QuickTime in web pages. The object view helpers take care of embedding media with minimum effort.

There are four initial Object helpers:

  • htmlFlash() Generates markup for embedding Flash files.
  • htmlObject() Generates markup for embedding a custom Object.
  • htmlPage() Generates markup for embedding other (X)HTML pages.
  • htmlQuicktime() Generates markup for embedding QuickTime files.

All of these helpers share a similar interface. For this reason, this documentation will only contain examples of two of these helpers.

Flash helper

Embedding Flash in your page using the helper is pretty straight-forward. The only required argument is the resource URI.

1
<?php echo $this->htmlFlash('/path/to/flash.swf'); ?>

This outputs the following HTML:

1
2
3
4
5
<object data="/path/to/flash.swf"
        type="application/x-shockwave-flash"
        classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
        codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
</object>

Additionally you can specify attributes, parameters and content that can be rendered along with the <object>. This will be demonstrated using the htmlObject() helper.

Customizing the object by passing additional arguments

The first argument in the object helpers is always required. It is the URI to the resource you want to embed. The second argument is only required in the htmlObject() helper. The other helpers already contain the correct value for this argument. The third argument is used for passing along attributes to the object element. It only accepts an array with key-value pairs. classid and codebase are examples of such attributes. The fourth argument also only takes a key-value array and uses them to create <param> elements. You will see an example of this shortly. Lastly, there is the option of providing additional content to the object. Now for an example which utilizes all arguments.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
echo $this->htmlObject(
    '/path/to/file.ext',
    'mime/type',
    array(
        'attr1' => 'aval1',
        'attr2' => 'aval2'
    ),
    array(
        'param1' => 'pval1',
        'param2' => 'pval2'
    ),
    'some content'
);

/*
This would output:

<object data="/path/to/file.ext" type="mime/type"
    attr1="aval1" attr2="aval2">
    <param name="param1" value="pval1" />
    <param name="param2" value="pval2" />
    some content
</object>
*/

InlineScript Helper

The HTML <script> element is used to either provide inline client-side scripting elements or link to a remote resource containing client-side scripting code. The InlineScript helper allows you to manage both. It is derived from HeadScript, and any method of that helper is available; however, use the inlineScript() method in place of headScript().

Note

Use InlineScript for HTML Body Scripts

InlineScript, should be used when you wish to include scripts inline in the HTML body. Placing scripts at the end of your document is a good practice for speeding up delivery of your page, particularly when using 3rd party analytics scripts.

Some JS libraries need to be included in the HTML head; use HeadScript for those scripts.

JSON Helper

When creating views that return JSON, it’s important to also set the appropriate response header. The JSON view helper does exactly that. In addition, by default, it disables layouts (if currently enabled), as layouts generally aren’t used with JSON responses.

The JSON helper sets the following header:

1
Content-Type: application/json

Most AJAX libraries look for this header when parsing responses to determine how to handle the content.

Usage of the JSON helper is very straightforward:

1
<?php echo $this->json($this->data) ?>

Note

Keeping layouts and enabling encoding using Zend_Json_Expr

Each method in the JSON helper accepts a second, optional argument. This second argument can be a boolean flag to enable or disable layouts, or an array of options that will be passed to Zend_Json::encode() and used internally to encode data.

To keep layouts, the second parameter needs to be boolean TRUE. When the second parameter is an array, keeping layouts can be achieved by including a keepLayouts key with a value of a boolean TRUE.

1
2
3
4
5
// Boolean true as second argument enables layouts:
echo $this->json($this->data, true);

// Or boolean true as "keepLayouts" key:
echo $this->json($this->data, array('keepLayouts' => true));

Zend_Json::encode allows the encoding of native JSON expressions using Zend_Json_Expr objects. This option is disabled by default. To enable this option, pass a boolean TRUE to the enableJsonExprFinder key of the options array:

1
2
3
4
<?php echo $this->json($this->data, array(
    'enableJsonExprFinder' => true,
    'keepLayouts'          => true,
)) ?>
Edit this document

Edit this document

The source code of this file is hosted on GitHub. Everyone can update and fix errors in this document with few clicks - no downloads needed.

  1. Login with your GitHub account.
  2. Go to View Helpers on GitHub.
  3. Edit file contents using GitHub's text editor in your web browser
  4. Fill in the Commit message text box at the end of the page telling why you did the changes. Press Propose file change button next to it when done.
  5. On Send a pull request page you don't need to fill in text anymore. Just press Send pull request button.
  6. Your changes are now queued for review under project's Pull requests tab on GitHub.