Monday, July 15, 2013

Setting a default page title in Zend Framework and modifying per action

Specifying the Page Title

The site or business name as part of the page title and then we are adding additional information based on the location or page within the site. As an example, the techinfotricks.com website includes the string " techinfotricks.com " on all pages, and the prepends information based on the page: "About US - techinfotricks.com ". Within Zend Framework, the headTitle() view helper can help simplify this task.

The headTitle() helper allows you to aggregate content for the <title> tag.

You can control the order using prepend() and append(), and provide a separator to use between segments using the setSeparator() method.

Typically, you should specify any segments common to all pages in your bootstrap, similar to how we define the doctype. In this case, we'll define a _initPlaceholders() method for operating on all the various placeholders, and specify an initial title as well as a separator.

    class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
    {
        // ...    
        protected function _initDoctype()
      { 
        $this->bootstrap('view');
        $view = $this->getResource('view');
        $view->doctype('XHTML1_STRICT');
        $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
        $viewRenderer->setView($view);
        $view->headTitle('Techinfo Tricks Solutions')->setSeparator(' :: ');
       }
        // ...
    }

Within a view script, we might want to add another segment:

// place after other segments
<?php $this->headTitle()->append('Some Page'); ?>
   
// place before
<?php $this->headTitle()->prepend('Some Page'); ?>


In our layout, we will simply echo the headTitle() helper:
<?php echo $this->doctype() ?>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <?php echo $this->headTitle(); ?>        
        <link rel="stylesheet" type="text/css" href="<?php echo $this->baseUrl('css/stylesheet.css'); ?>" />           </head>
    <body>
       .............................
       .............................
       .............................
    </body>
</html>

This will generate the following output:
    <!-- If append() was used: -->
  <title>Techinfo Tricks Solutions :: Some Page</title>
    
    <!-- If prepend() was used: -->
<title>Some Page :: >Techinfo Tricks Solutions </title> 

Another way to modifying the title in the action on controller.

public function aboutusAction()
{
    $this->view->headTitle()->prepend('About US');
}
 

This will generate the following output:

<title> Techinfo Tricks Solutions :: About US</title>




No comments:

Post a Comment