Magento – Add child to a layout block programmatically

blockslayoutmagento-1

I want to add "children" to a given layout (custom-) block.

In my layout-xml:

<block type="core/text_list" name="custom_html_blocks_body_end" as="custom_html_blocks_body_end">
    ...
    <block type="page/html" name="custom_svg_icons" as="custom_svg-icons" template="my_templates/custom_svg-icons.phtml" />
    ...
</block>

The block i want to add childs programmatically is custom_svg_icons.

In custom_svg-icons.phtml:

<?php $this->getChildHtml(); ?>

And in my script to set the children:

$objSVG = $this->getLayout()->createBlock('page/html')->setTemplate('my_templates/svg_image.phtml')->setData(array('imageName'=>'svg-image-demo'));
$objSVGBlock = $this->getLayout()->getBlock('custom_svg-icons')->append($objSVG);

I get no Error, but nothing happens. There is no child.

Best Answer

Not sure if that work but try

$objSVG = $this->getLayout()->createBlock('page/html')->setTemplate('my_templates/svg_image.phtml')->setData(array('imageName'=>'svg-image-demo'));

$objSVGBlock = $this->getLayout()->getBlock('custom_svg-icons');

$objSVGBlock->setChild('svg_image',$objSVG);

Or might be you will need to call toHtml after set the child.

$objSVGBlock->toHtml();