2

How can I get intercept html output in magento2?

For example, for magento 1.x i can do:

///core_block_abstract_to_html_after
$block = $observer->getBlock();
if($block->getNameInLayout() == 'root'){
    $output = $observer->getTransport()->getHtml();
}

In magento2 the to_html_after event was remote?: [https://github.com/magento/magento2/blob/0.42.0-beta10/lib/internal/Magento/Framework/View/Element/AbstractBlock.php#L622][1]

1
  • 1
    Looks like core_block_abstract_to_html_after has been replaced by core_layout_render_element. Dec 22, 2015 at 13:04

1 Answer 1

3

You can use plugins/interceptors.
For Magento 1 it wasn't even a good practice to use the event core_block_abstract_to_html_after. That one got dispatched for all blocks and observing it would create an overhead.
With plugins/interceptors you can get your hands on the html for a specific block.
You can read this documentation
Just to explain in a few words...

you need to add this in the di.xml of your module

<type name="NameOfClass\You\Intercept\Here">
    <plugin name="some-unique-name-here" type="Your\Class\Name\Here" sortOrder="1" />
</type>

NameOfClass\You\Intercept\Here is the name of the core block you want to get your hands on.
Your\Class\Name\Here is the class your create in order do your changes.
It's similar to the observer in Magento 1.

<?php 
namespace Your\Class\Name;
class Here 
{
    //'after' is reserved word. 
    //`ToHtml` is the name of the method your want to intercept, capitalized
    //in this case you want to intercept the toHtml method of a certain block
    //the first parameter is always the name of the class you intercept with the reserved word `Inteceptor` at the end. This will give you access at the class instance
    //the second parameter is what the original toHtml method returns. This is the html you want
    public function afterToHtml(
         \NameOfClass\You\Intercept\Here\Interceptor $original,
         $html
    ) {
        //do something with $html
        //make sure you return a value of the same type as the original method
        return $html;

    }
}
2
  • Thanks Marius. The only question: in magento 1.xx I find block by block name in layout, now should i use block classname directly? I know, that the plugin will work with child objects, but what will happen if the class will be replaced?
    – sergei.sss
    Jul 31, 2015 at 14:58
  • @sergei.sss. Good question. I'm afraid I'm not that advanced to answer it.
    – Marius
    Jul 31, 2015 at 15:00

Your Answer

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

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