Magento 2 – How to Pass Variable to Template from Another Template

blocksmagento2template

I want to pass product as variable from list.phtml to another template file which i will called there using below code

echo $this->getLayout()->createBlock("Magento\Framework\View\Element\Template")->setTemplate("Test_Module::Test/view/config.phtml")->toHtml();

I've found that for Magento 1 we can use below code.

echo $this->getLayout()->createBlock('module/template_name')
->setData('key', 'some value')
->setTemplate('module/newblock.phtml')->toHtml(); 

And we can access of this variable to that template using below syntax

echo $this->key;

I've tried same for Magento 2 using below code but no luck.

echo $this->getLayout()->createBlock("Magento\Framework\View\Element\Template")->setData('key', 'd')->setTemplate("Test_Module::Test/view/config.phtml")->toHtml(); 

I can see blank page when tried to get value using below code.

echo $this->key;

Anyone have tried similar to it?

Best Answer

I tried this it's worked for me

<?php echo $this->getLayout()->createBlock("Magento\Framework\View\Element\Template")->setKey('dfd')->setTemplate("Test_Module::Test/view/config.phtml")->toHtml(); ?>

to get value

$block->getKey();

also change your method will work too

 echo $this->key;

to

echo $this->getKey();
Related Topic