Magento 2 – Replacement for Product Type Specific Layout Handles

layoutmagento2productupdate-handle

In Magento 1, we had some specific layout handles for each product types:

  • <PRODUCT_TYPE_simple>
  • <PRODUCT_TYPE_configurable>
  • <PRODUCT_TYPE_grouped>
  • <PRODUCT_TYPE_bundle>
  • <PRODUCT_TYPE_virtual>
  • <PRODUCT_TYPE_downloadable>

It has been explained on this post that those handles were deprecated in Magento 2: Magento2. Layout Handle customer_logged_in

Question is: what do we use instead of those handles ?

Best Answer

After some research here is what I've found.

In Magento 2, you can use the following layout files to handle product type specific pages:

  • catalog_product_view_type_simple.xml
  • catalog_product_view_type_configurable.xml
  • catalog_product_view_type_grouped.xml
  • catalog_product_view_type_bundle.xml
  • catalog_product_view_type_virtual.xml
  • catalog_product_view_type_downloadable.xml

Magento 2 adds this specific handle via the initProductLayout method of Magento\Catalog\Helper\Product\View :

$resultPage->addPageLayoutHandles(
        ['id' => $product->getId(), 'sku' => $urlSafeSku, 'type' => $product->getTypeId()]
    );

In that particular case, the addPageLayoutHandles method adds the three following layout handle:

  • catalog_product_view_id_productid
  • catalog_product_view_sku_productsku

Hey! that's a new handle that wasn't present on M1

  • and finally catalog_product_view_type_producttype

Full detail of the addPageLayoutHandles method:

public function addPageLayoutHandles(array $parameters = [], $defaultHandle = null)
{
    $handle = $defaultHandle ? $defaultHandle : $this->getDefaultLayoutHandle();
    $pageHandles = [$handle];
    foreach ($parameters as $key => $value) {
        $pageHandles[] = $handle . '_' . $key . '_' . $value;
    }
    // Do not sort array going into add page handles. Ensure default layout handle is added first.
    return $this->addHandle($pageHandles);
}

On top of that, it will also support your custom product type for instance if you create a product type with the name "test" you can then create a file called catalog_product_view_type_test.xml to handle specific layouts for this type of products.

Related Topic