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 Answer 1

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.

6
  • If i have 5-10 variables then i have to create each individual function?
    – Jackson
    Commented Sep 13, 2016 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. Commented Sep 13, 2016 at 9:50
  • Ok got it. Instead of Controller file Can i define in Block file app\code\Custom\Module\Block\Index.php?
    – Jackson
    Commented Sep 13, 2016 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 Commented Sep 13, 2016 at 9:55
  • Why i'm asking so i can save that controller 3 Lines
    – Jackson
    Commented Sep 13, 2016 at 9:57

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.