4

I would like to do a custom product layout for product in a specific attribute set. In Magento 1 we could create a layout handle for a specific attribute set.

What is the best way to do this in Magento 2? Is there a 'designed' way of being able to do this in the xml files?

Marius
  • 197,939
  • 53
  • 422
  • 830
David W
  • 124
  • 7

1 Answers1

4

I haven't tried this, but it seams like the place to start:
When rendering the product page, eventually this is called: Magento\Catalog\Helper\Product\View::initProductLayout.
In this method, at one point this is called:

   if ($params && $params->getAfterHandles()) {
        foreach ($params->getAfterHandles() as $handle) {
            $resultPage->addPageLayoutHandles(
                ['id' => $product->getId(), 'sku' => $urlSafeSku, 'type' => $product->getTypeId()],
                $handle
            );
        }
    }

So you may be able to create a before plugin for this method.
(Here is a tutorial about creating plugins).
In this plugin you can just alter the $params param and attach to it some after handles.

something like this:

public function beforeInitProductLayout(
    \Magento\Catalog\Helper\Product\View $view,
    \Magento\Framework\View\Result\Page $resultPage,
    $product,
    $params = null
)
{
   if ($product in the right attribute set) {
       if (!$params) {
           $params = new \Magento\Framework\DataObject();
       }
       $afterHandles = $params->getAfterHandles();
       if (!$afterHandles) {
           $afterHandles = array();
       }
       $afterHandles[] = 'your_layout_handle_here';
       $params->setAfterHandles($afterHandles);
   }
   return [$resultPage, $product, $params];
}

then create the layout handle [Namespace]/[Module]/view/frontend/layout/your_layout_handle_here.xml where you put your layout changes.

Marius
  • 197,939
  • 53
  • 422
  • 830