ARTICLE

Magento 2 Custom Widgets: widget.xml Parameters, Block Classes, Templates, and Rendering Widgets on a Hyva Storefront

Magento 2 Custom Widgets: widget.xml Parameters, Block Classes, Templates, and Rendering Widgets on a Hyva Storefront

A Magento 2 custom widget is a block class declared in widget.xml so admins can place it in CMS content or on any page without touching code. You define parameters in XML, read them as block data, and render a template. On Hyva, the template needs Tailwind and Alpine markup and widget instances must be reassigned to the new theme.

Widgets are one of the most useful handoffs between developers and merchandising teams, and one of the least documented. The common tutorials build a text field and a template and stop. This guide covers the full widget.xml schema, how the directive is actually rendered, the difference between inline widgets and widget instances, caching, and the specific work a Hyva storefront adds.

What a widget is in Magento 2

A widget has three parts:

  1. A declaration in etc/widget.xml that names the widget, points to a block class, and lists the parameters an admin can fill in.
  2. A block class that implements Magento\Widget\Block\BlockInterface.
  3. One or more .phtml templates.

Admins use the widget in two ways. They can insert it inline into a CMS page or block through the editor, which stores a directive in the content. Or they can create a widget instance under Content > Elements > Widgets, which places the block into a layout container on chosen pages. The same declaration serves both, but the two routes behave differently in storage, theme scoping, and caching.

Magento ships a set of native types. Adobe’s widget documentation lists 15, including CMS Static Block, CMS Page Link, Catalog Products List, Catalog New Products List, Catalog Category Link, Recently Viewed Products, and Orders and Returns. A custom widget is worth building when a team keeps asking for the same content pattern with different values: a promo tile, a store locator teaser, a brand strip, a size guide link.

The widget.xml schema

The schema is defined in widget.xsd in the Magento_Widget module. A realistic declaration looks like this:

<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
    <widget id="vendor_promo_tile" class="Vendor\Promo\Block\Widget\Tile"
            placeholder_image="Vendor_Promo::images/widget_tile.png">
        <label translate="true">Promo Tile</label>
        <description translate="true">Image, heading, and link tile</description>
        <parameters>
            <parameter name="heading" xsi:type="text" visible="true" required="true" sort_order="10">
                <label translate="true">Heading</label>
            </parameter>
            <parameter name="show_button" xsi:type="select" visible="true" sort_order="20"
                       source_model="Magento\Config\Model\Config\Source\Yesno">
                <label translate="true">Show Button</label>
            </parameter>
            <parameter name="button_label" xsi:type="text" visible="true" sort_order="30">
                <label translate="true">Button Label</label>
                <depends>
                    <parameter name="show_button" value="1"/>
                </depends>
                <value>Shop now</value>
            </parameter>
            <parameter name="template" xsi:type="select" visible="true" required="true" sort_order="40">
                <label translate="true">Template</label>
                <options>
                    <option name="default" value="widget/tile/default.phtml" selected="true">
                        <label translate="true">Default tile</label>
                    </option>
                    <option name="compact" value="widget/tile/compact.phtml">
                        <label translate="true">Compact tile</label>
                    </option>
                </options>
            </parameter>
        </parameters>
    </widget>
</widgets>

The widget node requires id and class. Optional attributes are is_email_compatible, placeholder_image, and ttl. It requires a label and a description, and may contain parameters and containers. Add Magento_Widget to the sequence in your module.xml so the declaration loads in the right order.

One caution on ttl. The schema allows it and core widgets such as the products list set ttl="86400", but in the current 2.4-develop source the widget config converter reads only id, class, is_email_compatible, and placeholder_image. Do not rely on ttl to cache your widget. Caching is something you add in the block, covered below.

Parameter types

The XSD defines exactly five parameter types. Anything else you see in a tutorial is not part of the schema.

xsi:type Admin control Notes
text Single line input Optional <value> child sets a default
select Dropdown Options inline in <options> or from a source_model attribute
multiselect Multiple select Same option sources as select; the value arrives as a comma-separated string
block Custom chooser A child <block class="..."> renders a picker, as core does for CMS blocks and products
conditions Rule conditions builder Requires a class attribute; core uses it for the products list

Each parameter takes name (required), visible, required, and sort_order, and may contain label, description, and depends. A depends node hides the field until another parameter has a given value, which keeps long forms manageable for content teams.

The template parameter and containers

A parameter named template is a convention the widget system understands. Because every parameter becomes block data, a template value sets the block’s template directly. That is how one widget offers several layouts.

The optional containers node ties templates to layout containers for widget instances:

<containers>
    <container name="sidebar.main">
        <template name="compact" value="compact"/>
    </container>
    <container name="content">
        <template name="default" value="default"/>
        <template name="compact" value="compact"/>
    </container>
</containers>

The value of each template refers to the name of an option on the template parameter. With this in place, an admin who chooses the sidebar container is only offered the compact template. Without a containers node, all templates are offered for every container. Core’s new products widget uses this to keep wide grids out of sidebars. If container names are unfamiliar, our guide to Magento 2 layout XML explains them.

The block class and template

Adobe’s custom widget tutorial shows the minimum block:

namespace Vendor\Promo\Block\Widget;

use Magento\Framework\View\Element\Template;
use Magento\Widget\Block\BlockInterface;

class Tile extends Template implements BlockInterface
{
    protected $_template = 'widget/tile/default.phtml';
}

BlockInterface declares only addData() and setData(), which Template already provides. The interface is a marker, and it matters: the filter that renders widgets returns an empty string for any block that does not implement it.

Parameters arrive as block data, so the template reads them with getData():

<?php /** @var \Magento\Framework\Escaper $escaper */ ?>
<div class="promo-tile">
    <h2><?= $escaper->escapeHtml($block->getData('heading')) ?></h2>
    <?php if ($block->getData('show_button')): ?>
        <a href="<?= $escaper->escapeUrl($block->getData('link_url')) ?>">
            <?= $escaper->escapeHtml($block->getData('button_label')) ?>
        </a>
    <?php endif; ?>
</div>

Escape every parameter on output. Values are typed by admin users and stored as plain strings, and some published tutorials echo them raw. Use escapeHtml, escapeHtmlAttr, or escapeUrl according to where the value lands.

Keep logic out of the template. If the widget needs to load products or call a service, put that in the block or in a view model. On Hyva projects the second option is the norm.

How an inline widget is stored and rendered

When an admin inserts a widget into CMS content, Magento\Widget\Model\Widget::getWidgetDeclaration() builds a directive in this form:

{{widget type="Vendor\Promo\Block\Widget\Tile" heading="Winter sale" show_button="1" template="widget/tile/default.phtml"}}

A few details of that method explain behavior that confuses people:

  • Empty parameters are dropped from the directive, so a blank field means the key is absent, not an empty string.
  • Array values from a multiselect are joined with commas.
  • Every value is passed through attribute escaping when the directive is created.
  • A conditions parameter is stored as conditions_encoded.

At render time, Magento\Widget\Model\Template\Filter::generateWidget() parses the directive and creates the block with the parameters as data. Two failure modes are silent. If the type is not declared in any widget.xml, the filter returns an empty string. If the class does not implement BlockInterface, it also returns an empty string, with no log entry. When a widget “disappears” after a module is disabled or a class is renamed, this is why, and the directive text stays in the CMS content pointing at a class that no longer resolves.

That last point is a migration risk. Inline directives hold the fully qualified class name. Renaming or moving a widget block class breaks every CMS page that uses it, so treat widget class names as a public contract once content teams have started using them.

Widget instances: layout updates and theme scoping

A widget instance is stored in the database, not in content. The relevant tables are widget_instance (type, theme, title, store IDs, and parameters stored as JSON), widget_instance_page (page group, layout handle, and container reference), and the layout_update and layout_link tables that hold the generated XML.

On save, Magento generates a layout update that places the block in the chosen container, on handles derived from your selection. “All Pages” becomes the default handle and “All Product Types” becomes catalog_product_view. The chosen template must be in the allowed list for that container or the save throws an exception.

The detail that matters most for a redesign is theme scoping. A widget instance requires a theme, and its layout link is keyed by theme ID. Adobe’s widget creation guide tells admins to confirm the Design Theme matches the current theme. The practical consequence: instances assigned to a Luma theme do not apply once the store switches to a Hyva theme. They are still in the admin grid, but nothing renders on the storefront until each one is reassigned or recreated for the new theme. Inline widgets in CMS content are not affected by this, because they are not tied to a theme.

Caching a custom widget

A custom widget block gets no block cache by default. Its output is rendered on every uncached page request and then stored as part of the full page cache entry. For a simple tile that is fine. For a widget that loads a collection, it is worth adding block caching the way core does.

The core products list widget is the reference. It implements IdentityInterface, sets a cache_lifetime of 86400 seconds and product cache tags, defines getCacheKeyInfo() with the store, theme, customer group, page, conditions, and template, and returns identities from getIdentities(). A custom widget needs the same three things if it shows entity data:

  • A cache key that includes every parameter that changes the output. Two tiles with different headings must not share a key.
  • A lifetime, or the block is not cached at all.
  • Identities, so that saving the underlying product or CMS block purges the pages that show it.

Without identities, the widget keeps showing stale data until the full page cache is cleared by hand. Our article on full page cache and Varnish on Hyva goes deeper on how tags travel to the cache layer.

Saving a widget instance in the admin invalidates the block_html and layout cache types when its page groups or parameters change, so expect the cache management notice after edits.

Rendering widgets on a Hyva storefront

The widget system is PHP and layout XML, so it works on Hyva unchanged. What changes is the template. Hyva removes RequireJS, jQuery, and Knockout from the storefront, so a widget template written for Luma that depends on them renders markup but its behavior is dead. Three things need attention.

Templates

Rewrite the .phtml with Tailwind utility classes and, where it needs interactivity, Alpine.js. For a widget in your own module, the clean pattern is a Hyva compatibility module. Per the Hyva documentation, a compat module is registered in etc/frontend/di.xml through Hyva\CompatModuleFallback\Model\CompatModuleRegistry, and a template placed at the same relative path in the compat module overrides the original automatically on Hyva themes. The Luma template stays in place for any store still on Luma, which is useful during a phased rollout.

For core widgets, check the Hyva default theme before assuming coverage. Hyva’s documentation does not publish a list of supported core widget templates. The default theme repository includes templates for the catalog products list grid, product link, recently viewed, and CMS link widgets; verify any other type on a staging site.

Tailwind class scanning

Tailwind only generates CSS for classes it finds in scanned files. Classes used in a widget template inside app/code or vendor are missing from the compiled stylesheet unless that module is in the content paths. Hyva’s Tailwind purge settings documentation describes the options: add the module path as a source in the theme’s Tailwind configuration, or register the module so it is written to app/etc/hyva-themes.json by bin/magento hyva:config:generate. Compatibility modules are registered for Tailwind automatically. We cover the build side in Hyva Tailwind production build.

A related trap: do not build class names from parameters, such as 'bg-' . $block->getData('color'). Tailwind cannot see a class that only exists at runtime. Map parameter values to complete class names in PHP instead.

Instances and content after the switch

As described above, widget instances have to be reassigned to the Hyva theme. Plan it as a content task with an inventory: export the instance grid, decide which ones are still wanted, and recreate those. This is a normal line item when our Hyva development services team scopes a migration, alongside the Page Builder content review described in Page Builder on Hyva.

Widgets compared with the alternatives

A widget is not the only way to give content teams reusable blocks. On Magento the usual alternatives are a CMS block with fixed HTML, which needs no code but has no parameters, and a Page Builder content type, which gives a visual editor but is far more work to build. A widget sits between them: structured fields, developer-controlled markup, modest build cost.

Other platforms solve the same problem with their own models. Shopify themes use sections and blocks with schema settings, Shopware uses CMS elements in Shopping Experiences, and BigCommerce has Page Builder widgets. The principle carries over even though the code does not: give editors typed fields, keep markup in version control.

A release checklist for a custom widget

  1. widget.xml validates against the XSD and uses only the five parameter types.
  2. Every parameter is escaped in every template.
  3. The block implements BlockInterface, and the class name is final before content teams use it.
  4. containers restricts templates where a layout would break.
  5. Cache key, lifetime, and identities are set if the widget shows entity data.
  6. On Hyva: template rewritten, module registered for Tailwind, no runtime-built class names.
  7. Existing widget instances inventoried and reassigned to the active theme.
  8. Tested inline in a CMS page, inline in a CMS block, and as an instance in each allowed container.

Bemeir builds and supports Magento and Hyva storefronts from Brooklyn. See our Magento development services, read about Bemeir, or browse the technology partners we integrate with.

FAQ

What parameter types can a Magento 2 widget use?

The widget XSD defines five: text, select, multiselect, block, and conditions. Select and multiselect take options inline or from a source model class. The block type renders a custom chooser such as the CMS block or product picker, and conditions renders the rule builder used by the catalog products list.

Why does my custom widget render nothing on the storefront?

The widget filter returns an empty string, without logging, when the type in the directive is not declared in a widget.xml or when the block class does not implement Magento\Widget\Block\BlockInterface. A disabled module or renamed class causes the same result. For widget instances, also check that the instance is assigned to the active theme.

Do widget instances carry over when switching from Luma to Hyva?

Not automatically. Each widget instance is assigned to a theme and its layout update is linked by theme ID, so instances created for a Luma theme stop rendering when the store uses a Hyva theme. Reassign or recreate them. Inline widgets inside CMS pages and blocks are not theme scoped and keep rendering.

Does the ttl attribute in widget.xml cache my widget?

Do not count on it. The schema accepts ttl and core widgets set it, but the current widget config converter does not read it. To cache a widget, set cache_lifetime and a cache key in the block, and implement IdentityInterface so related entity saves purge the output.

Why are Tailwind classes in my widget template missing on Hyva?

Tailwind only compiles classes it finds in scanned files. A template in app/code or vendor is not scanned unless the module is added to the theme’s Tailwind sources or registered so it appears in app/etc/hyva-themes.json. Classes assembled from parameter values at runtime are never found.

Let us help you get started on a project with Magento 2 Custom Widgets: widget.xml Parameters, Block Classes, Templates, and Rendering Widgets on a Hyva Storefront and leverage our partnership to your fullest advantage. Fill out the contact form below to get started.

more articles about ecommerce

Read on the latest with Shopify, Magento, eCommerce topics and more.