Magento – Magento 2: Use Custom Variable in Layout File

blockscustomlayoutmagento2module

We can use Magento default variables in layout file using

<item name="link" xsi:type="string">{{baseUrl}}</item>

I would like to create one variable in Block File & Use it. Like

protected function _prepareLayout() {
    parent::_prepareLayout();

    $this->myVar = 'google.com';

    return $this;
}

In layout file

<item name="link" xsi:type="string">{{myVar}}</item>

Can i define & access it or i have to manage through Controller file?

Best Answer

Pretty sure it's possible.

What you can do first is add a protected variable to your block class:

protected $_myVar;

Then you can define a public method to retrieve this variable:

public function getMyVar()
{
     return $this->_myVar;
}

Then in your controller action method you can do the following:

$resultLayout = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_LAYOUT);
$block = $resultLayout->getLayout()->getBlock('block.name');
$myVar = $block->getMyVar();

Please note that you'll have to replace block.name with the name of the block declared in your layout.

Related Topic