How to use dynamic URL parameters in Magento 2 to change layout for A/B testing and display different content

In Magento 2, you can use dynamic URL parameters to change the layout for A/B testing and display different content. You can achieve this through the following steps:

1. app/code/DMTQ/Catalog/etc/events.xml

<event name="layout_load_before">
<observer name="layout_change_event_listener" instance="DMTQ\Catalog\Observer\LayoutChangeEventListener" />
</event>

2. app/code/DMTQ/Catalog/Observer/LayoutChangeEventListener.php


namespace DMTQ\Catalog\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\App\RequestInterface;

class LayoutChangeEventListener implements ObserverInterface
{
/**
* Request
* @var RequestInterface
*/
protected RequestInterface $_request;

/**
* Class constructor
* @param RequestInterface $request
*/
public function __construct(
RequestInterface $request,
)
{
$this->_request = $request;
}

public function execute(Observer $observer)
{
$layout = $observer->getLayout();
$fullActionName = $observer->getFullActionName();
if ($fullActionName === 'catalog_product_view') {
$ad = $this->_request->getParam('ab');
if ($ad == 'b') {
$layout->getUpdate()->addHandle('catalog_product_view_b');
}
}
}
}


Copyright © 2013-present Magento, Inc. All rights reserved.