10

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 ...>
 <arguments>
 <argument name="escaper" xsi:type="object">Magento\Framework\Escaper</argument>
 </arguments>
</block>

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?

asked Jul 8, 2020 at 8:38

1 Answer 1

16

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 = [])
{
 ob_start();
 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) {
 ob_end_clean();
 throw $exception;
 }
 /** Get output buffer. */
 $output = ob_get_clean();
 return $output;
}
answered Jul 8, 2020 at 9:04
3
  • 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/… Commented Jul 8, 2020 at 10:46
  • Kind of stupid that there is no Getter to access this variable inside Blocks. 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 Commented May 9, 2022 at 12:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.