Zend Framework Custom View Helper to add Default Meta Content
Posted on | July 17, 2012 | 2 Comments
This post will share a custom View Helper that will check for your application adding empty meta details, and if there are, populating the values with default values from the application config.ini file.
First, we need to do add a folder structure for our view helpers. Create the following tree structure:
[php]
root
|->application
|->library
|->Zend
|->RPK
|->View
|->Helper
[/php]
Now, we need to tell our application where to find our view helper. In the application bootstrap.php file add the following function:
[php]
bootstrap(‘view’);
$view = $this->getResource(‘view’);
$view->addHelperPath(‘RPK/View/Helper’, ‘RPK_View_Helper’);
}
[/php]
This allows the application to access our view helper.
Here is the code for the view helper. We extend the already existing Zend view helper ‘HeadMeta’. Feel free to download this file
[php]
type == ‘name’ AND ($value->content == null OR strlen($value->content) === 0) AND ($value->name == ‘keywords’ OR $value->name == ‘description’))
{
//get options
$config = Zend_Controller_Front::getInstance()->getParam(‘bootstrap’)->getOptions();
switch ($value->name)
{
case ‘keywords’:
$setting = $config[‘default’][‘meta’][‘keywords’];
break;
case ‘description’:
$setting = $config[‘default’][‘meta’][‘description’];
break;
}
//set the value
if ($setting)
{
$value->content = $setting;
}
}
if (!$this->_isValid($value))
{
$e = new Zend_View_Exception(‘Invalid value passed to append; please use appendMeta()’);
$e->setView($this->view);
throw $e;
}
return $this->getContainer()->append($value);
}
[/php]
Usage
[php]
headMeta();
[/php]
[php]
page = page object passed to view script from controller
$this->headMeta()
->setName(‘keywords’, $this->page->metaKeywords)
->setName(‘description’, $this->page->metaDesc);
[/php]
As you can see there is no special instantiation code needed.
Posted By:Richard Parnaby-King