TransWikia.com

magento2 plugin and str_replace

Magento Asked by Boll on December 11, 2020

In file module magento have function

public function formatPrecision(
    $price,
    $precision,
    $options = [],
    $includeContainer = true,
    $addBrackets = false
) {
    if (!isset($options['precision'])) {
        $options['precision'] = $precision;
    }
    if ($includeContainer) {
        return '<span class="price">' . ($addBrackets ? '[' : '') . $this->formatTxt(
            $price,
            $options
        ) . ($addBrackets ? ']' : '') . '</span>';
    }
    return $this->formatTxt($price, $options);
}

I write di.xml

<type name="MagentoDirectoryModelCurrency">
    <plugin name="afterFormatPrecision" type="CommercersPriceItempropPluginCurrency" sortOrder="1"/>
</type>

And i have afterFormatPrecision

public function afterFormatPrecision(
    MagentoDirectoryModelCurrency $subject
){
    return str_replace('<span class="price">','<span class="price" itemprop="price">','<span class="price">');
}

But function after not working. Please help me!

2 Answers

Magento doesn't allow this (itemprop) attribute, that's why when passing content to escapeHtml who remove your itemprop attribute. Here is the allowed attribute list:

private $allowedAttributes = ['id', 'class', 'href', 'title', 'style'];

Check the following class: vendor/magento/framework/Escaper.php

private function removeNotAllowedAttributes(DOMDocument $domDocument)
{
    $xpath = new DOMXPath($domDocument);
    $nodes = $xpath->query(
        '//@*[name() != '' . implode('' and name() != '', $this->allowedAttributes) . '']'
    );
    foreach ($nodes as $node) {
        $node->parentNode->removeAttribute($node->nodeName);
    }

    foreach ($this->notAllowedAttributes as $tag => $attributes) {
        $nodes = $xpath->query(
            '//@*[name() ='' . implode('' or name() = '', $attributes) . '']'
            . '[parent::node()[name() = '' . $tag . '']]'
        );
        foreach ($nodes as $node) {
            $node->parentNode->removeAttribute($node->nodeName);
        }
    }
}

You can overwrite following phtml for your modification:

vendor/magento/module-catalog/view/base/templates/product/price/amount/default.phtml

Answered by Sohel Rana on December 11, 2020

Your after plugin arguments are wrong, you need to add the $result argument in order to make a replacement.

Try the following:


public function afterFormatPrecision(
    MagentoDirectoryModelCurrency $subject,
    $result
){
    return str_replace('<span class="price">','<span class="price" itemprop="price">', $result);
}

Source: link

Answered by Rus0 on December 11, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP