2

How do I get current category "page_layout" value? e.g "1 column" or "2 column" and so on. The values from Layout screen shoot bellow.

enter image description here

2 Answers 2

4

I wanted to achieve the exact same thing. I ended up creating a helper class that injects both \Magento\Framework\View\Result\Page and \Magento\Framework\View\Layout.

The Page object can retrieve the selected layout using the method named getConfig()->getPageLayout(). But this method will return NULL if the page layout has not been selected in the admin area. So I ended up adding a custom method that will return the default page layout if no layout has been selected.

Helper class example

<?php

namespace {VendorName}\{ModuleName}\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper
{

    /**
     * @var \Magento\Framework\View\Result\Page
     */
    protected $_pageResult;

    /**
     * @var \Magento\Framework\View\Layout
     */
    protected $_layout;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\View\Layout $layout,
        \Magento\Framework\View\Result\Page $pageResult)
    {
        $this->_pageResult = $pageResult;
        $this->_layout = $layout;

        parent::__construct($context);
    }

    /**
     * Will return the currect page layout.
     *
     * @return string The current page layout.
     */
    public function getCurrentPageLayout()
    {
        $currentPageLayout = $this->_pageResult->getConfig()->getPageLayout();

        if (is_null($currentPageLayout))
        {
            return $this->_layout->getUpdate()->getPageLayout();
        }

        return $currentPageLayout;
    }
}

Template file usage

<?php

$data = $this->helper('{VendorName}\{ModuleName}\Helper\Data');

echo '<pre> Page Layout:' , $data->getCurrentPageLayout(), '</pre>';

This might not be the best way to achieve this, but with Magento2's lack of documentation for developers, this is the only solution I could find that works in later versions of Magento2. I hope this helps!

1

You can inject BuilderInterface to your constructor

public function __construct(
        \Magento\Framework\View\Model\PageLayout\Config\BuilderInterface $pageLayoutBuilder
    ) {
        $this->pageLayoutBuilder = $pageLayoutBuilder;
}

public function getLayouts() {
    $pageLayout = [];
    $pageLayout = $this->pageLayoutBuilder->getPageLayoutsConfig()->toOptionArray();    
    unset($pageLayout[0]);
    return $pageLayout;
}
1
  • your code returns null. no matter what column I set to. thanks Nov 23, 2017 at 9:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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