سؤال

In Magento 1 I used the code below for value:

value="<?php echo $this->escapeHtml($this->getDefaultValue()) ?>

How could I set this code in Magento 2?

هل كانت مفيدة؟

المحلول

/**
 * Escaper
 *
 * @var \Magento\Framework\Escaper
 */
protected $_escaper;

public function __construct(
\Magento\Framework\Escaper $_escaper
) {
    $this->_escaper=$_escaper
}

Now you can easily use escapeHtml by

$this->_escaper->escapeHtml($data, $allowedTags);

Or If you are using any block or .phtml file then you can use this by

<?= $block->escapeHtml($block->getDefaultValue()); ?>

EDIT[As per requested]

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$escaper = $objectManager->create('Magento\Framework\Escaper')->escapeHtml($data);

نصائح أخرى

You can use it in magento-2 like below

value="<?php echo $block->escapeHtml($block->getDefaultValue()) ?>"

With the latest version of Magento 2.4 now you can directly use $escaper variable to use class \Magento\Framework\Escaper. The $escaper local variable is available inside the any .phtml templates.

<?= $escaper->escapeHtml($block->getDefaultValue()); ?>

Read More at: XSS prevention strategies

Another way is to use the method "html_entity_decode"(http://php.net/manual/en/function.html-entity-decode.php) like this

echo html_entity_decode ( $_helper->productAttribute($_product, $_product->getName(), 'name') )

Since magento/framework 100.2.0 you can call escape methods using $block variable in template files.

All available escape methods can be found in \Magento\Framework\View\Element\AbstractBlock class.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى magento.stackexchange
scroll top