Zend Framework 2 : Reset HeadTitle Position from View
Sometime, we need to reset position of title that default we can look at ZendSkeletonApplication like “My Album – ZF2 Skeleton Application” to something like “ZF2 Skeleton Application – My Album”.
We CAN NOT do this from view :
$this->headTitle($title, 'PREPEND'); //OR $this->headTitle($title, 'APPEND');
because of the layout rendered after view rendered, so we need to pass a value from view to layout via placeholder. So after set a title at view, we need to pass a value via placeholder view helper.
// module/Album/view/album/album/index.phtml: $title = 'My albums'; $this->headTitle($title); $this->placeholder('titleType')->set('PREPEND');
so we can set the title type at layout like the following :
// module/Application/view/layout/layout.phtml: echo $this->headTitle('ZF2 Skeleton Application', $this->placeholder('titleType', 'APPEND')) ->setSeparator(' - ')->setAutoEscape(false);
$this->placeholder(‘titleType’, ‘APPEND’) that passed at 2nd parameter of headTitle() means that if titleType already set, so get from the already data, if no, set to ‘APPEND’ as default value.
When situation need to remove layout title ( parameter is ‘SET’), and use the view title, we need to make a conditional like this :
// module/Application/view/layout/layout.phtml: if ($this->placeholder('titleType', 'APPEND') == 'SET') { echo $this->headTitle()->setAutoEscape(false); } else { echo $this->headTitle('ZF2 Skeleton Application', $this->placeholder('titleType', 'APPEND')) ->setSeparator(' - ')->setAutoEscape(false); }
That’s it 😉
references:
1. http://stackoverflow.com/questions/13949809/zend-framework-2-make-content-page-variable-accessable-in-layout-phtml
2. http://zf2.readthedocs.org/en/latest/modules/zend.view.helpers.placeholder.html#zend-view-helpers-initial-placeholder
There is some small possibility that it was inspied by this issue 🙂
https://github.com/zendframework/zf2/issues/4810
But I forgot to say Thanks for this post!
No. I’m not inspired by that issue :). You’re welcome!
You can also pass a variable to your layout from your view using $this->layout()->titleType = ‘APPEND’;
Great!