Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Specifying Stylesheets with HeadLink

Good CSS developers will often create a general stylesheet for sitewide styles, and individual stylesheets for specific sections or pages of the website, and load these latter conditionally so as to decrease the amount of data needing to be transferred on each request. The headLink() placeholder makes such conditional aggregation of stylesheets trivial within your application.

To accomplish this, headLink() defines a number of "virtual" methods (via overloading) to make the process trivial. The ones we will be concerned with are appendStylesheet() and prependStylesheet(). Each takes up to four arguments, $href (the relative path to the stylesheet), $media (the MIME type, which defaults to "text/css"), $conditionalStylesheet (which can be used to specify a "condition" under which the stylesheet will be evaluated), and $extras (an associative array of key and value pairs, commonly used to specify a key for "media"). In most cases, you will only need to specify the first argument, the relative path to the stylesheet.

In our example, we'll assume that all pages need to load the stylesheet located in "/styles/site.css" (relative to the document root); we'll specify this in our _initPlaceholders() bootstrap method.

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
    // ...

    protected function _initPlaceholders()
        $view = $this->getResource('View');

        // Set the initial title and separator:
        $view->headTitle('My Site')
             ->setSeparator(' :: ');

        // Set the initial stylesheet:

    // ...

Later, in a controller or action-specific view script, we can add more stylesheets:

<?php $this->headLink()->appendStylesheet('/styles/user-list.css'?>

Within our layout view script, once again, we simply echo the placeholder:

<?php echo $this->doctype() ?>
    <?php echo $this->headTitle() ?>
    <?php echo $this->headLink() ?>
    <!-- ... -->

This will generate the following output:

<link rel="stylesheet" type="text/css" href="/styles/site.css" />
<link rel="stylesheet" type="text/css" href="/styles/user-list.css" />

Zend Framework