Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 42 ยท Requests and Output

Blocks, ViewModels and PHTML Templates

Learn how Magento blocks, ViewModels and .phtml templates work together, how to pass arguments from layout XML, and how to escape output safely.

Layout XML decides which pieces appear on a page. Blocks and templates decide what those pieces print. A block is a PHP object attached to a place in the layout tree. A template is a .phtml file, which is just PHP mixed with HTML, that the block renders. A ViewModel is a plain class that holds the logic a template needs so that neither the block nor the template becomes a dumping ground.

This lesson shows the three together: the block class, the template it renders, and the ViewModel pattern that modern Magento code prefers. It also covers the most important habit in template work: escaping every value you print. Real Magento files are read-only. The runnable examples are stand-ins built from ordinary PHP, which is a fair model because a .phtml file really is PHP.

A block and its template

The layout file from Layout XML and Handles declares a block:

XML
<block class="Acme\Hello\Block\Greeting"
       name="acme.greeting"
       template="Acme_Hello::greeting.phtml"/>

The block class normally extends Magento\Framework\View\Element\Template:

PHP
<?php

namespace Acme\Hello\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;

class Greeting extends Template
{
    public function __construct(Context $context, array $data = [])
    {
        parent::__construct($context, $data);
    }

    public function getVisitorName(): string
    {
        return (string) $this->getData('visitor_name');
    }
}

The constructor takes the template Context, which bundles the services every block needs, and a $data array. Pass both to the parent. Extra constructor arguments you add are injected like anywhere else (The Object Manager and Constructor Injection); put them before $data, which stays last.

The template is view/frontend/templates/greeting.phtml in the module. The part before :: in the layout attribute is the module name, and the rest is the path inside templates:

PHP
<?php
/** @var \Acme\Hello\Block\Greeting $block */
/** @var \Magento\Framework\Escaper $escaper */
?>
<p class="greeting">
    <?= $escaper->escapeHtml(__('Hello, %1!', $block->getVisitorName())) ?>
</p>

Three details are worth copying into every template you write:

  • The @var comments at the top tell your editor what $block and $escaper are. They are not executed, but they give you autocomplete and catch mistakes.
  • $block is the block object. Call its public methods to get data.
  • $escaper escapes output. In Magento 2.4 this variable is available in templates, and it is the preferred way; older code calls $block->escapeHtml(), which still works in many versions but is the older style.

<?= ... ?> is PHP's short echo tag. For a quick recap of PHP inside HTML, see PHP and HTML.

Always escape on output

Anything that came from a visitor, a database, a configuration field or a product description can contain HTML. If you print it unescaped, an attacker can inject script into your page: cross-site scripting (XSS). The general idea is explained in XSS and Output Escaping. Magento's escaper has one method for each place a value can land:

Where the value goes Method
Between tags: <p>HERE</p> escapeHtml()
Inside an attribute: title="HERE" escapeHtmlAttr()
In a URL: href="HERE" escapeUrl()
Inside JavaScript escapeJs()

The right method depends on the context, so pick by where the value is printed, not by where it came from. A few more rules:

  • Escape at the moment of output, in the template, not earlier. Then the template makes the safety visible.
  • Wrap translated strings too: escapeHtml(__('Hello')), because translation files are data too.
  • When you really must print trusted HTML (for instance a CMS block), use the allowed-tags form of the escaper, and understand where that HTML comes from.
  • Never use echo $block->getSomething() for anything text-like without escaping.

Passing arguments from layout XML

Layout can hand data to a block with argument nodes, and the block (or template) reads it with getData():

XML
<block class="Acme\Hello\Block\Greeting" name="acme.greeting"
       template="Acme_Hello::greeting.phtml">
    <arguments>
        <argument name="visitor_name" xsi:type="string">Guest</argument>
        <argument name="show_icon" xsi:type="boolean">true</argument>
    </arguments>
</block>

Common types are string, number, boolean, array and object. Inside the block, $this->getData('visitor_name') or the magic getter getVisitorName() returns the value. Arguments are a good way to let a theme change a template's behavior without touching PHP.

ViewModels keep logic out of blocks and templates

Early Magento 2 code put logic into block classes, and every block ended up extending something big. The modern pattern is to keep the block thin and pass a ViewModel: a small class that implements Magento\Framework\View\Element\Block\ArgumentInterface and has whatever methods the template needs.

PHP
<?php

namespace Acme\Hello\ViewModel;

use Magento\Framework\View\Element\Block\ArgumentInterface;

class Greeting implements ArgumentInterface
{
    public function __construct(private \Acme\Hello\Model\VisitorNames $names)
    {
    }

    public function getDisplayName(): string
    {
        return $this->names->current() ?: 'Guest';
    }
}

It is attached through layout as an object argument. Because a ViewModel is created by dependency injection, its own constructor can ask for any service:

XML
<arguments>
    <argument name="view_model" xsi:type="object">Acme\Hello\ViewModel\Greeting</argument>
</arguments>

And the template reads it:

PHP
<?php
/** @var \Magento\Framework\View\Element\Template $block */
/** @var \Magento\Framework\Escaper $escaper */
/** @var \Acme\Hello\ViewModel\Greeting $viewModel */
$viewModel = $block->getData('view_model');
?>
<p><?= $escaper->escapeHtml($viewModel->getDisplayName()) ?></p>

Why bother? The block can be the stock Template class, so you write no block at all. The ViewModel is easy to unit test (Testing Magento Code), and templates stay readable. Keep the roles clear:

  • Template: markup and loops, plus escaping. No queries, no business rules.
  • Block: the connection to layout, children and rendering. Keep it small.
  • ViewModel: the data and decisions the template needs.
flowchart LR
    A["Layout XML<br/>block + arguments"] --> B["Block<br/>(often plain Template)"]
    A --> C["ViewModel<br/>(object argument)"]
    B --> D["greeting.phtml"]
    C -->|"getData('view_model')"| D
    D --> E["escaper -> HTML"]

Layout wires a block to a template and a ViewModel; the template asks the ViewModel for data and escapes it as it prints.

Rendering children works from the template too: $block->getChildHtml('child.name') prints one child block, and $block->getChildHtml() prints all of them.

Try it: a block, a template and an escaper

A .phtml file is a PHP file, so the stand-in below uses a function holding PHP and HTML as the template, and a plain block class around it. The Escaper is a minimal version of the real one: it handles HTML, attributes and URL schemes, nothing more. The visitor name is deliberately hostile.

PHP Rendering a template with escaping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The script tag is printed as harmless text, the double quotes in the attribute become &quot;, and the javascript: URL is replaced with #. The child block appears where getChildHtml('footer') was called.

Try it: a ViewModel behind a thin block

This second stand-in follows the ViewModel pattern. The ViewModel gets a data source through its constructor, a simple stand-in for injected services, and decides what to show. The template only prints. Swapping the data source changes the page without touching the template.

PHP A ViewModel feeding a template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

All the decisions are in PriceViewModel. It is trivial to test with a fake PriceSource, and renderPriceBox (the stand-in for the template) never knows where prices come from.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a .phtml file?

    Templates are plain PHP files with HTML around them. The block renders them and exposes itself as $block.
  2. 2. Which method should you use to print a value inside a normal HTML attribute?

    Pick the escaper by context. Attributes need escapeHtmlAttr, URLs need escapeUrl, and text between tags needs escapeHtml.
  3. 3. What does a ViewModel implement so that it can be passed as a block argument?

    Magento\Framework\View\Element\Block\ArgumentInterface marks classes meant to be passed to blocks as object arguments.
  4. 4. Where should business logic that a template needs live in modern Magento code?

    ViewModels hold the logic, are injected with services and are easy to test. The template should only print and loop.

Summary

  • A block connects a layout node to a .phtml template; the template's first lines declare $block and $escaper for the editor.
  • Reference templates as Module_Name::path.phtml; they live in view/<area>/templates/.
  • Escape every printed value with the method that matches its context: HTML, attribute, URL or JavaScript.
  • Layout argument nodes pass strings, numbers, booleans, arrays and objects into a block.
  • Use ViewModels (ArgumentInterface) for the logic a template needs, and keep blocks and templates thin.

Next, learn how Magento finds templates and assets across themes in The Theme System and Frontend Assets.