26

I've found that when trying to use the unsetChild method, sometimes I have to use the 'name' attribute and others 'as'. It seems that if a block is added normally, you use 'as' but if it is added to a block using the append method, you may have to use 'name'. Is this assumption correct?

What is the reasoning behind this and is there a standard way to understand which attribute you should use?

15

Block can always be referenced by name. Alias (as) is used to simplify the long name of a block and the only differs with the scope. Name has to be unique within the page and alias within a parent block.

  • 5
    I'm afraid none of that is true. In template, you cannot reference a block by its name if it has an alias set. You can only use the alias.As for the uniqueness of alias, quite the opposite is true -- alias was introduced to make it possible for a different block to be rendered without changing template. – Jan Tomka Feb 17 '13 at 10:07
  • 5
    @JanTomka has given the main use of aliases. It should be pointed out that while the statement that "you cannot reference a block by its name if it has an alias set" is generally true, there is a method named getBlockHtml() which is sometimes used to render blocks by name. – benmarks Feb 17 '13 at 15:43
6

When you use as, you can call $this->getChildHtml("as_value") on the phtml template.

The name must be unique, and can be used for < reference > blocks, < remove >, etc.

For example (catalog.xml):

<block type="catalog/product_view" name="product.info" template="catalog/product/view.phtml">
    <block type="catalog/product_view_media" name="product.info.media" as="media" template="catalog/product/view/media.phtml"/>
</block>

If you open catalog/product/view.phtml you'll see:

<div class="product-img-box">
    <?php echo $this->getChildHtml('media') ?>
</div>

You see? as="media", and then $this->getChildHtml('media')...

5

Nobody has answered the particular question about unsetChild yet. Methods related to children of a block always refer to child blocks by alias, which is only known to the parent and unlike the name, not globally unique.

But if the block was created without defining an alias, the alias defaults to the name.

So in short, if the child block has an explicit alias, you must use the alias. If not, use the name.

Aliases are given by as="..." if the block was created as child block via XML, or by action parameter if they were moved around or dynamically added with methods like append(), insert() or setChild().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.