Blog
Shop
About us
Contact us

Dynamically add widget to .phtml file in Magento template

frontend2

Recently I downloaded a Magento module that seemed to do what I want:  a list of tweets of a certain user, displayed in the frontend of Magento.

However, the module was a widget. I did not want to create a CMS page or block solely for inputting the widget’s variable so I sorted out how to call the widget from inside a .phtml file in a Magento template.

The widget was Magentweet and had several things to configure when using it in the backend. I could add the same widget programmatically like this:

<?php $tweetblock =  $this->getLayout()->createBlock(‘magentweet/user’);

$tuser = $tweetblock->setData(‘tuser’,'groupdeal_nl’);

$nb = $tweetblock->setData(‘nb’, 5);

$link = $tweetblock->setData(‘link’,'#1E7EC8′);

$link_a = $tweetblock->setData(‘link_a’,'#000′);

$desa = $tweetblock->setData(‘desa’,'enable’);

echo $tweetblock->setTemplate(‘magentweet/user.phtml’)->toHtml(); ?>

Of importance here is not that a widget block is created through a regular createBlock() statement. The trick is the setData() statements. In a widgets Block code you can easily see which data the widget expects, and you can set the widget’s data accordingly from the template instead of through elaborate WYSIWYG cms procedures.

The Author of this post is sander

Versatile web enthusiast. Specialized in e-commerce and the technology behind that.

1 Responses »

Trackbacks

  1. Twitted by netimagenl

Leave a Comment