Before 2.4 the way you could sanitize an html value in a template was to use $block->escapeHtml($valueHere);.
Where $blick is the instance of the current block.
This still works in 2.4, but the method is deprecated.

 * Escape HTML entities
 * @param string|array $data
 * @param array|null $allowedTags
 * @return string
 * @deprecated Use $escaper directly in templates and in blocks.
public function escapeHtml($data, $allowedTags = null)
    return $this->_escaper->escapeHtml($data, $allowedTags);

The recommendation is to use the escaper directly in the templates.
But I cannot add the escaper instance as a view model in the template because Magento\Framework\Escaper does not implement Magento\Framework\View\Element\Block\ArgumentInterface.
So if I do this in my layout files

<block ...>
        <argument name="escaper" xsi:type="object">Magento\Framework\Escaper</argument>

I get an exception

Instance of Magento\Framework\View\Element\Block\ArgumentInterface is expected, got Magento\Framework\Escaper instead.

Is there another clean way to use escape the html values in a template?

1 Answer 1


In 2.4 simply calling $escaper->escapeHtml() works.
$escaper is an instance of Magento\Framework\Escaper sent directly to the template in the same way as $block is an instance of the current block class. It's all done in Magento\Framework\View\TemplateEngine\Php::render()

public function render(BlockInterface $block, $fileName, array $dictionary = [])
    try {
        $tmpBlock = $this->_currentBlock;
        $this->_currentBlock = $block;
        extract($dictionary, EXTR_SKIP);
        //So it can be used in the template.
        $escaper = $this->escaper; // <-- here it is
        // phpcs:ignore
        include $fileName;
        $this->_currentBlock = $tmpBlock;
    } catch (\Exception $exception) {
        throw $exception;
    /** Get output buffer. */
    $output = ob_get_clean();
    return $output;
  • 4
    Weirdly it doesn't seem to be in the release notes but it is in the dev docs. devdocs.magento.com/guides/v2.4/extension-dev-guide/…
    – Ben Crook
    Commented Jul 8, 2020 at 10:46
  • Kind of stupid that there is no Getter to access this variable inside Blocks.
    – Max
    Commented May 8, 2022 at 21:50
  • I don't think there is a need to access it via EVERY block. If you need it in the template, it's there. If you need it in a block class you inject it as a dependency
    – Marius
    Commented May 9, 2022 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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