Finally, I can print all loaded xml layout and know how magento 2 layout is working. It also help us to check whether our custom module layout is loaded or not.
The idea is :
1/ We create a new directory Sample/Dev
.
Create Sample/Dev/registration.php
to declare with Magento 2 about our module directory.
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Sample_Dev',
__DIR__
);
2/ Create Sample/Dev/etc/module.xml
: To let Magento 2 know about setup version of our module
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="module.xsd">
<module name="Sample_Dev" setup_version="1.0.0" schema_version="1.0.0" release_version="1.0.1">
</module>
</config>
3/ Create Sample/Dev/etc/frontend/events.xml
. In this file, we will listen to event “layout_generate_blocks_after”
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="layout_generate_blocks_after">
<observer name="thienphucvx_layout_generate_blocks_after" instance="Sample\Dev\Model\Layout" />
</event>
</config>
4/ Create Sample/Dev/Model/Layout.php
with the content as below
<?php
namespace Sample\Dev\Model;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class Layout implements ObserverInterface
{
protected $_logger;
public function __construct ( \Psr\Log\LoggerInterface $logger
) {
$this->_logger = $logger;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$xml = $observer->getEvent()->getLayout()->getXmlString();
/*$this->_logger->debug($xml);*//*If you use it, check ouput string xml in var/debug.log*/
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/layout_block.xml');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info($xml);
return $this;
}
}
5/ Set up new module .
In your home website directory. enter CMD command line:
– php bin/magento module:enable Sample_Dev
– php bin/magento setup:upgrade
6/ Refresh the page that you want to see xml file (for example: your home page) and check your handle xml file in var/log/layout_block.xml
.