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')

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


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


also change your method will work too

 echo $this->key;


echo $this->getKey();
  • 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.
    – Kul
    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.
    – Kul
    Commented Apr 26, 2017 at 11:27

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.