Skip to content

Component templates

Conventions

Magewire templates conventionally reside in a directory view/frontend/templates/magewire/.

Usually component and template names match.
For example, a component My\Module\Magewire\ExampleForm will use a template view/frontend/templates/magewire/example-form.phtml.

If a block with a Magewire view model is not assigned a template, Magewire will default to a template name following this convention.

Inside Magewire component templates, the component instance is available through a $magewire template variable, hence it is not necessary to call $block->getData('magewire') and assign the instance to a variable yourself.

Required single root element

A Magewire component template must have a single root element.
If multiple root DOM elements are present, Magewire will not properly update the section of the component after values change.

The following example is correct, because there is only a single <div> root element:

<div>
    <ul>
        <?php foreach ($magewire->items as $item): ?>
        <li><?= $escaper->escapeHtml($item->getName()) ?></li>
        <?php endforeach; ?>
    </ul>
    <div>Total count: <?= (int) count($magewire->items) ?></div>
</div>

The following example is WRONG, because there are two root elements:

<div>
    <ul>
        <?php foreach ($magewire->items as $item): ?>
        <li><?= $escaper->escapeHtml($item->getName()) ?></li>
        <?php endforeach; ?>
    </ul>
</div>
<div>
    Total count: <?= (int) count($magewire->items) ?>
</div>

The following is another example of an invalid component template, because the leading text also counts as a second root node:

Total count: <?= (int) count($magewire->items) ?>
<div>
    <ul>
        <?php foreach ($magewire->items as $item): ?>
        <li><?= $escaper->escapeHtml($item->getName()) ?></li>
        <?php endforeach; ?>
    </ul>
</div>

Rendering component values

Inside a template, you can interact with any methods and properties of the $magewire instance.

You can call any view model method to render its returned value:

<div>
    <?= __('A method return value: %1', $magewire->loadSomeData()) ?>
</div>

There are several ways to read $magewire properties:

<div>
    <?= __('Using direct access: %1', $magewire->myprop) ?>
</div>
<div>
    <?= __('Via magic getter: %1', $magewire->getMyprop()) ?>
</div>
<div>
    <?= __('The magic "has" method, analog to isset(): %1', $magewire->hasMyprop()) ?>
</div>

Note

If you are familiar with Magento backend development, it might be surprising that Magewire provides magic get and has methods for properties, but no magic set method is available.

$component->setFoo($newValue); // WILL NOT WORK

Instead, use direct assignment

$component->foo = $newValue;
The reason there are no magic setters is because it matches components in Livewire, who also provide only magic get and has methods.