Pass a variable to a .phtml block

Here’s a simple snippet to pass a PHP variable from a controller ( or whatever magento file ) to a block, using the createBlock() method.

When you call a block:

1
2
3
4
5
<?php

$this->getLayout()->createBlock('module/template')
->setData('key', 'value')
->setTemplate('mediarepository/latest.phtml')->toHtml();

with the setData() method you’ll be able to acces your variable with:

1
2
3
<?php

$this->key;

In the mood for some more reading?

...or check the archives.