cancel
Showing results for 
Search instead for 
Did you mean: 

Inject widget from custom module into custom theme template

Inject widget from custom module into custom theme template

Hi,

Using Magento 2.4.3 (and higher soon).


I have a custom module which creates a widget. The widget is there to display a row of images.

I can create a block in Admin and add the widget to it successfully. 

 

What I would like to do is adding this widget dynamically to a phtml file (`Magento_Catalog/tempates/html/content.phtml`) in my custom theme, so that I can decide which image to add depending on the situation.

 

So far I have looked at solution like this one:

$widgetParams = ['id' => 'my_widget_id', 'galleryname' => 'default', ...]; // Params to add to widget dynamically
echo $this->getLayout() ->createBlock(\Magento\Framework\View\Element\Template::Class) ->setTemplate('MyVendor_MyModule::widget/image_section.phtml')
->setData('widget_parameters', $widgetParams) ->toHtml();

`image_section.phtml` being my widget template from my module. 

Unfortunately the above doesn't really work.

I can see that the widget starts being rendered but it doesn't generate correctly.

 

This is the html when I inspect:

<div class="bootstrap-grid" gallery="">
<div class="row">
</div>
</div>

`gallery` for example should be set to "default" and there should be much more content with images etc... 

 

Any help with this would be highly appreciated.

 

Thank you.

1 REPLY 1

Re: Inject widget from custom module into custom theme template

I reply to my own question.

 

The way I am calling the widget from inside the phtml of my custom theme is correct.

One of the problems above was that the way I passed the data.

Instead of 

setData('widget_parameters', $widgetParams)

it should have been

setData($widgetParams)

But for whoever is looking to do something similar, it works! 

 

cheers