2

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?

1

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.

  • If i have 5-10 variables then i have to create each individual function? – Ankit Shah Sep 13 '16 at 9:49
  • @MikeSmith it's up to you. You can also declare one single function that returns an array that contains all your variables. – Raphael at Digital Pianism Sep 13 '16 at 9:50
  • Ok got it. Instead of Controller file Can i define in Block file app\code\Custom\Module\Block\Index.php? – Ankit Shah Sep 13 '16 at 9:53
  • @MikeSmith I'm not too sure. It will only work if the layout has been loaded and if you can access which is usually done via the action classes – Raphael at Digital Pianism Sep 13 '16 at 9:55
  • Why i'm asking so i can save that controller 3 Lines – Ankit Shah Sep 13 '16 at 9:57

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.