I've declared a plugin that creates and adds a block programmatically if a condition is true. However, my code outputs nothing, it's like if the created block is not rendered at all.
etc/di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\View\Element\AbstractBlock">
<plugin name="Vendor_Module" type="Vendor\Module\Plugin\AppendBlockPlugin"/>
</type>
</config>
Plugins/AddBlockPlugin.php
public function beforeToHtml(AbstractBlock $block)
{
if (($block instanceof Block\Product\View)
&& $block->getNameInLayout() === 'product.info'
) {
$template = 'Vendor_Module::block.phtml';
$block->addChild(
'custom_block',
\Vendor\Module\Block\Block::class,
compact('template')
);
}
}
I've made some debugging to this code to ensue that the custom block renders without any errors and that the ->addChild
method is actually being called, but still no output for the block I added.
Best Answer
You can do this by event.
use event:
On this event add your block to
product.info
.Event:
Also, your parent template file means
product.info
you need to add the codeto show the child block content