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?
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 = [])
{
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;
}
-
4Weirdly 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– Ben Crook2020年07月08日 10:46:23 +00:00Commented Jul 8, 2020 at 10:46
-
Kind of stupid that there is no Getter to access this variable inside Blocks.Max– Max2022年05月08日 21:50:48 +00:00Commented 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 dependencyMarius– Marius2022年05月09日 12:37:57 +00:00Commented May 9, 2022 at 12:37