Zend: How to add webpage title in all my views?

Student picture Student · May 14, 2011 · Viewed 10.7k times · Source

For now I have to add title in all my views separately like this:

<head>
       <title>TestProject - Home</title>
</head>

and

<head>
       <title>TestProject - Dashboard</title>
</head>

Now if I want to change TestProject part of title then I have to change it in all my views. How can I mentioned this in BootStrap.php and add it in all views? And whenever I have to change this, I will change this in one place.

Answer

Eugene M picture Eugene M · May 14, 2011

You should look into the headTitle view helper. You can put this snippet below in your bootstrap file (from the documentation at http://framework.zend.com/manual/en/zend.view.helpers.html#zend.view.helpers.initial.headtitle).

// 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('Test Project');

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

Then you can set each page title individually in controller like this:

$this->view->headTitle('The page name')

The rendered title will look like this:

<title>Test Project / The page name</title>

Oh, and you need this in your layout script where the tag would go:

<?php echo $this->headTitle() ?>