Something I recently found out, is a feature that all blocks have. Interestingly enough, it wasn’t part of the Frontend certification, maybe because it isn’t used very much. I decided to dig into it anyway.
It’s pretty simple - Mage_Core_Block_Abstract
has the ability to group it’s children blocks without the need to use text lists.
The blockgroup API
The API looks something like this:
addToChildGroup($groupname, Mage_Core_Block_Abstract $child)
Unfortunately, you cannot call this function in layout XML because you can’t pass a block to a method - the XML parser doesn’t work that way. That means you can only create a group programmatically by using this method. But fear not, check out the next method and its implementation:
public function addToParentGroup($groupName)
{
$this->getParentBlock()->addToChildGroup($groupName, $this);
return $this;
}
This adds the block that’s executing the method to it’s parent block group.
Next up:
getChildGroup($groupName, $callback = null, $skipEmptyResults = true)
Documentation states:
* Get a group of child blocks
*
* Returns an array of <alias> => <block>
* or an array of <alias> => <callback_result>
* The callback currently supports only $this methods and passes the alias as parameter
That means you can render a group with the following code (stolen from catalog/product/view.phtml
):
foreach ($this->getChildGroup('detailed_info', 'getChildHtml') as $alias => $html) {
echo $html;
}
It’s interesting that you can pass a callback to getChildGroup
- the first time I see something like this in Magento. This means you can do something like:
$group = getChildGroup('detailed_info', getCacheLifetime)
...and get all cache lifetimes. I’m not quite sure why you would ever want to pass something other than getChildHtml
, but it’s possible.
Why use this over text list blocks?
By using a group, we don’t need to use a text_list
anymore and can keep our block hierarchy simpler:
block
block-1-1
block-1-2
block-2-1
block-2-2
block
text-list
block-1-1
block-1-2
text-list
block-2-1
block-2-2
What about Magento 2?
As far as I can see, Magento 2 doesn't have this feature. However, with the current state that Magento 2 is at, there is plenty of time for the codepool to change.