I have to pass a variable to a block .phtml file. I am setting layout in the controller by setTemplate() function. Do you have any idea?


2 Answers 2


Here I have a solution might work for you. We mostly use setData() method for pass variables from the controller to block.

$variableValue = 10000;
$block = $this->getLayout()->getBlock('blockNameHere');
$block->setData('variable', '$variableValue')->setTemplate('pathto/block.phtml');

above setData() method will create a variable, and you can access this variable in the block file block.phtml you created. Use below code for getting the value of the variable.

echo $this->variable;

simple example to pass a variable from Magento (template, controller, etc) file to a block with php code.

Call a block using the createBlock() method:

echo $this->getLayout()->createBlock('module/template_name')
->setData('key', 'some value')

The setData() method in the above code creates a variable, and you can access the variable with below code in the code that handles the block you created:

echo $this->key;

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.