Magento Block Names and Aliases

Magento allows you to add names and aliases to your blocks when adding a block within layout XML configuration. This is done by defining a block with name and as attributes.

<block type="core/template" name="module.custom.block" as="custom_block" template="custom/template.phtml" />

Often it is unclear what the purpose of these attributes are used for.

When defining a block, the name should be unique. You can then use this name when creating a <reference>.

<?xml version="1.0"?>
<layout>
    <default>
        <block type="core/template" name="module.custom.block" as="custom_block" template="custom/template.phtml" />

        <reference name="module.custom.block">
            <!-- Add code here -->
        </reference>
    </default>
</layout>

The block alias, as, is just used to simplify the long name of a block and the only differs with the scope.

If a block contains both name and as attributes and these values are different, when using $this->getChildHtml(), the alias value should be passed in as a parameter.

<?php echo $this->getChildHtml('custom_block');

Aliases are not required when defining blocks, so if one doesn’t exist, the block name can be used within $this->getChildHtml().

There are a couple of different ways to remove blocks within Magento. Either using the <remove> node, or using the unsetChild action method.

For example, to remove the search bar in the RWD theme: the search block is defined in the catalogsearch.xml file.

// app/design/frontend/rwd/default/layout/catalogsearch.xml

<reference name="header">
    <block type="core/template" name="top.search" as="topSearch" template="catalogsearch/form.mini.phtml"/>
</reference>

You can use the <remove> method, for example, in your custom theme’s local.xml file.

// app/design/frontend/[your_package]/[your_theme]/layout/local.xml

<?xml version="1.0"?>
<layout>
    <default>
        <remove name="top.search" />
    </default>
</layout>

Where the name attribute is the name of the block, and not the alias.

This is contrary to using unsetChild, where if a block’s name and alias have been defined, the as value is used instead.

This might seem confusing as the alias value is added within a pair of <name> nodes.

// app/design/frontend/[your_package]/[your_theme]/layout/local.xml

<?xml version="1.0"?>
<layout>
    <default>
        <reference name="header">
            <action method="unsetChild">
                <name<topSearch</name>
            </action>
        </reference>
    </default>
</layout>

Similar to $this->getChildHtml(), if an alias has not been defined, you can use the block’s name attribute when using unsetChild().