Magento 2: Adding a Custom PHTML Template to Core Widget

Published by John on September 24, 2020 Under Magento

Recently, while developing a Magento 2 custom template, I wanted to use Magento’s Catalog Products List widget, but customize the default phtml template a bit, which for this widget is the ‘Products Grid Template’: product/widget/content/grid.phtml

It is, of course, possible to over-ride the template within a theme or plugin, but I wanted to leave the core template alone and instead add a new template to the dropdown, so that if anyone ever wanted to use the core styling, they could.

This is quite easy to do, by a few lines in your widget.xml.

Prerequisites

This assumes that you have a working Magento 2 module and are comfortable adding templates.

Adding an Additional Template

In my case, I wanted to add an option to the ‘Catalog Products List’ widget, which is located here: vendor/magento/module-catalog-widget/
view/frontend/templates/widget/category_list
However, you should be able to use this process to add/customize other widget options as well.

  1. First, determine the ID of the widget, in this case products_list. You can find this in the widget declaration here: vendor/magento/module-catalog-widget/etc/widget.xml
  2. In your plugin’s etc file, add this to your widget.xml file:
        <widget id="products_list">
            <parameters>
                <parameter name="template" xsi:type="select">
                    <options>
                        <option name="slider" value="COMPANY_PLUGIN::widget/category_list/custom.phtml">
                            <label translate="true">Custom Template</label>
                        </option>
                    </options>
                </parameter>
            </parameters>
        </widget>
    
    
  3. Flush Cache, Upgrade, etc: bin/magento setup:upgrade && bin/magento cache:clean
  4. You should now be able select and use your own template. In this example, the template would be located in your plugin here: view/frontend/templates/widget/category_list/custom.phtml

No Comments |

Add a Comment