2

In Magento 2.3.4 you can add custom layout update via XML files, using

cms_page_view_selectable_<PAGEIDENTIFIER>_<CUSTOMNAME>.xml

format.

But what if I want to apply this layout update on 20 CMS pages? Do I have to create a separate XML file for each page? Is there any way I can apply a layout update XML file on multiple CMS pages?

1

There is no way to apply an a layout update to multiple layout handles with just one XML file.

What you could do, is add a custom layout handle to all CMS pages where you want the layout to be updated. Then you can create one layout XML for that handle which is applied to all pages with that custom handle.

To do that you need to write a plugin for the prepareResultPage method of \Magento\Cms\Helper\Page. This can be done is your module by adding/modifing the folling files:

<module-dir>/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Cms\Helper\Page">
        <plugin sortOrder="1" name="vendorModulePage" type="Vendor\Module\Plugin\Helper\PagePlugin"/>
    </type>
</config>

<module-dir>/Plugin/Helper/PagePlugin.php

<?php

namespace Vendor\Module\Plugin\Helper;

class PagePlugin
{
    /**
     * @var \Magento\Cms\Model\Page
     */
    private $page;

    /**
     * PagePlugin constructor.
     * @param \Magento\Cms\Model\Page $page
     */
    public function __construct(
        \Magento\Cms\Model\Page $page
    ) {
        $this->page = $page;
    }

    /**
     * @param \Magento\Cms\Helper\Page $subject
     * @param \Magento\Framework\View\Result\Page|bool $result
     * @return \Magento\Framework\View\Result\Page|bool
     */
    public function afterPrepareResultPage(\Magento\Cms\Helper\Page $subject, $result)
    {
        if ($result instanceof \Magento\Framework\View\Result\Page) {
            if ($this->isHandleApplicable()) {
                $result->addHandle('cms_custom_handle');
            }
        }

        return $result;
    }

    /**
     * @return bool
     */
    private function isHandleApplicable()
    {
        if (in_array($this->page->getIdentifier(), ['identifier1', 'identifier2', 'home'])) {
            $isApplicable = true;
        } else {
            $isApplicable = false;
        }

        return $isApplicable;
    }
}

You can edit the isHandleApplicable method to match your needs. In my example the layout handle cms_custom_handle is added when the identifier of the current page is identifier1, identifier2 or home

You can now create a cms_custom_handle.xml that is applied to all pages that match your conditions in the isHandleApplicable method.

| improve this answer | |

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.