0

I have to create a template programmatically.
And so I need a master template with one child template. That child template again has two child templates.

Now I don't use a layout.xml file I need to call "setTemplate".
But how can I use "setTemplate" for the childs? MAgento can't find these child template because there is no reference to them.

I tried so far:

$layout = Mage::app()->getLayout();
$block = $layout->createBlock('core/template', 'master')
    ->setTemplate('default/html/master.phtml');
$blockChild1 = $layout->createBlock('core/template', 'master.child1')
    ->setTemplate('default/html/child1.phtml');
$blockChild1Child1 = $layout->createBlock('core/template', 'master.child1.child1')
    ->setTemplate('default/html/child1/child1.phtml');
$blockChild1Child2 = $layout->createBlock('core/template', 'master.child1.child2')
    ->setTemplate('default/html/child1/child2.phtml');


$blockChild1->setChild('master.child1', $blockItem);
$blockChild1->setChild('master.child1', $blockTotal);
$block->setChild('master', $blockInvoice);
$html = $block->toHtml();

1 Answer 1

1

This is a bit tricky, but here is a working version:

// Get layout
$layout = Mage::app()->getLayout();

// Master block
$master = $layout->createBlock('core/template', 'master')
    ->setTemplate('default/html/master.phtml');

// Child block
$child = $layout->createBlock('core/template', 'master.child1')
    ->setTemplate('default/html/child1.phtml');

// Children 1 block
$children1 = $layout->createBlock('core/template', 'master.child1.child1')
    ->setTemplate('default/html/child1/child1.phtml');

// Children 2 block
$children2 = $layout->createBlock('core/template', 'master.child1.child2')
    ->setTemplate('default/html/child1/child2.phtml');

// Set children 1 to child
$child->setChild('master.child1.child1', $children1);
// Set children 2 to child
$child->setChild('master.child1.child2', $children2);
// Set child to master
$master->setChild('master.child1',$child);

// Master to HTML
$html = $master->toHtml();

The template default/html/master.phtml will contain the following:

echo $this->getChildHtml('master.child1');

The template default/html/child1.phtml will contain the following:

echo $this->getChildHtml('master.child1.child1');
echo $this->getChildHtml('master.child1.child2');

And the templates default/html/child1/child1.phtml and default/html/child1/child2.phtml will contain the HTML or data. Unless you go a level deeper and call 3rd level child.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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