4

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?

1

1 Answer 1

8

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(); 
3
  • Its work but i've problem if block is different rather than Magento\Framework\View\Element\Template. I have another methods on block which i called there. Commented Apr 26, 2017 at 10:52
  • 1
    @Kul it doesnot matter just use $this->getKey() in your block it will work too. Commented Apr 26, 2017 at 10:54
  • Great Its work. I've another issue with block that's why it doesn't work first time. Commented Apr 26, 2017 at 11:27

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.