I would like to render a widget in my template by its ID, just like I have with blocks:

echo $block->getLayout()->createBlock('Magento\Cms\Block\Widget\Block')->setBlockId('widget_id')->toHtml();

With the way your doing it, you are hard coding the actual widget id. That would be fine but a better way is for you to be able to use a container where you can change the widget id through the admin, letting you easily change the widget any time you like. This can be done by creating a container on your default.xml which you can override through your theme on Magento_Theme/layout/default.xml see example xml for adding the custom container.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <referenceContainer name="main">
            <container name="example.block" label="Example Block" htmlTag="div" htmlClass="example-block" before="-" />

This will add a container which you can then use on the widget creation. In my example i used the main container as a reference but you can use any reference you would like depending on your needs.

location where you can find the widget layout container

| improve this answer | |
  • Thanks for this, what I was wanting to do was have an array of widget ids chosen by the user and saved in the General Options and then I can loop through them to display the widgets, if that makes sense? – greenarrow Dec 13 '17 at 8:52
  • Im not sure about what you mean by General options but what you can do is add the widgets to the same layout container. That way they will show on the same container. – Oliver Ong Dec 13 '17 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.