Magento – Adding rel=”next”/”prev” tags based upon pagination

collection;headermeta-tagsseo

For SEO purposes, I'm attempting to add link tags to the head block so that I can reference the previous and next blog pages like so:

<link rel="prev" href="http://citygear.dev/blog?p=4">
<link rel="next" href="hhttp://citygear.dev/blog?p=6">

FWIW, I'm using the AW_Blog extension, though that's not of great consequence here.

Question

How can I retrieve the paginated collection as it is loaded in the content block so that I can add these tags to the header?

The snippet of my layout XML:

    <reference name="head">
        <block type="core/template" name="canonical_blog" template="page/html/canonical_pager.phtml" />
    </reference>
    <reference name="content">
        <block type="blog/blog" name="blog" template="aw_blog/blog.phtml">
            <block type="blog/product_toolbar" name="aw_blog_list_toolbar" template="catalog/product/list/toolbar.phtml">
                <block type="page/html_pager" name="product_list_toolbar_pager"/>
            </block>
        </block>
    </reference>

What I've tried

Per the layout file above, I've tried to add a template to the head so that I can render the link tags. I've tried within that file to reference the product_list_toolbar_pager block (as shown below), but the collection isn't available when loaded in the header.

$pager_block = $this->getLayout()->getBlock('product_list_toolbar_pager');

$pager_block->getCollection()->getSize() returns a fatal error because $pager_block->getCollection() is null

EDIT

Per Amasty's answer below, I tried the following, but $this->pagerBlock->getCollection() is still null.

Add a new Block (AW_Blog_Block_Relpager) with the following constructor:

protected function _construct()
{
    /**
     * @var Mage_Core_Model_Layout
     */
    $layout = Mage::app()->getLayout();

    /**
     * @var Mage_Page_Block_Html_Head
     */
    $headBlock = $layout->getBlock('head');

    /**
     * @var Mage_Page_Block_Html_Pager|null
     */
    $pagerBlock = $layout->getBlock('product_list_toolbar_pager');
    $this->pagerBlock = $pagerBlock;

    $this->setTemplate('aw_blog/blog_rel.phtml');

    /**
     * Append block to header block
     */
    $headBlock->setChild('rel_paginator', $this);

    parent::_construct();
}

Referring to the layout above, I added the following immediately underneath product_list_toolbar_pager

                <block type="blog/relpager" name="rel_paginator" />

Best Answer

Add a new block after the items inside the content block.

Inside this block access the header and toolbar blocks as

$this->getLayout()->getBlock('name');

Related Topic