Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/sbboke.com/wp-content/plugins/wordpress-seo/src/integrations/front-end-integration.php:409) in /www/wwwroot/sbboke.com/wp-content/themes/pacify/content-single.php on line 5

Magento2 用货币符号格式化价格

我今天在搜索如何获取格式化价格,那里的帖子告诉我使用ObjectManager。这是一个可怕的主意!因此,这是正确的方法。

如果您需要获取格式化的价格,则最好将Magento 2中附带的货币添加为您自己的类的依赖项,以实现此目的的最佳方法。我们需要添加为依赖项的类是:Magento\Framework\Pricing\Helper\Data

该助手类有两种使用方法。该currency方法或currencyByStore方法。该currency方法将使用当前商店范围的货币。currencyByStore默认情况下以相同的方式工作,但是具有第二个可选参数来定义哪个商店。

方法签名:

currency($value, $format = true, $includeContainer = true)

currencyByStore($value, $store = null, $format = true, $includeContainer = true)

提示:$includeContainer参数值设置 为false会删除包含html的内容,您将只获得价格及其货币。

我们将其作为参数传递给__construct,然后将实例设置为类的受保护属性。请参阅以下示例:

<?php
namespace Namespace\Module\Model;

class MyClass {

    protected $pricingHelper;

    public function __construct(Magento\Framework\Pricing\Helper\Data $pricingHelper) 
    {
        $this->pricingHelper = $pricingHelper
    }

    public function getFormattedPrice($price, $format = true, $includeContainer = true)
    {
         return $this->pricingHelper->currency($price, $format, $includeContainer);
    }

}

您可能遇到过ObjectManager示例。这些是不良的做法。总是做额外的工作以正确地注入您的类,不要偷懒!从长远来看,依赖关系注入系统会更好,因为您的依赖关系已明确。

版权属于: sbboke版权所有。

转载时必须以链接形式注明作者和原始出处及本声明。

张贴在magento2教程标签:

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论