4

I am trying to work on a product subscriptions page which is very different in function from a standard product page. I have created my new Magento_Theme/page_layout/subscription.xml I set Magento 2 to use my custom layout for the product I want.

My question is, how do I create a custom set of layout instructions Magento_Catalog/layout/catalog_product_view.xmlto be used only with Magento_Theme/page_layout/subscription.xml ?

I still need most catalog_product_view pages to use the standard layout instructions. The main reason for this, is that subscription pages are going to be so different I need entirely different XML for the page layout.

Essentially, I would like to have a specific paired page_layout and layout for the subscription products.

Thanks!

0

There's a method called addPageLayoutHandles in Magento\Framework\View\Result\Page that you can make a plugin for, such as:

<?php

namespace Some\Module\Plugin;


use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\View\Result\Page;

class ProductLayout
{
    protected $productRepository;

    public function __construct(ProductRepositoryInterface $productRepository)
    {
        $this->productRepository = $productRepository;
    }

    public function beforeAddPageLayoutHandles(Page $subject, ...$args)
    {
        if (is_array($args) && count($args) == 1) {
            $params = $args[0];
            if (isset($params['sku'])) {

                $product = $this->productRepository->getById($params['id']);

                if ($product->getPageLayout() === 'subscription') {
                    $subject->getLayout()->getUpdate()->removeHandle($subject->getDefaultLayoutHandle());
                    return [$params, 'catalog_product_subscription'];
                }
            }
        }

        return $args;
    }
}

Basically this checks that the name of the page layout for the requested product is subscription and if so it removes the default layout handle (catalog_product_view) and adds the layout handle catalog_product_subscription.

Then you need a frontend layout file called catalog_product_subscription.xml containing your alternate layout code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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