在Magento2中获取当前货币符号

VIP*_*ROY 3 symbols currency magento magento2

如何在Magento2的.phtml文件中使用货币符号编写用于打印购物车总数的代码?

Muk*_*ain 9

protected $_currency;

public function __construct(
    \Magento\Backend\Block\Template\Context $context,       
    \Magento\Directory\Model\Currency $currency,        
    array $data = []
)
{           
    $this->_currency = $currency;       
    parent::__construct($context, $data);
}

/**
 * Get currency symbol for current locale and currency code
 *
 * @return string
 */ 
public function getCurrentCurrencySymbol()
{
    return $this->_currency->getCurrencySymbol();
}
Run Code Online (Sandbox Code Playgroud)


And*_*rea 5

这对我获取当前货币符号真正有用:

protected $_priceCurrency;

public function __construct(
  \Magento\Backend\Block\Template\Context $context,
  \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency,
  array $data = []
)
{           
  $this->_priceCurrency = $priceCurrency;
  parent::__construct($context, $data);
}

/**
 * Get current currency symbol
 *
 * @return string
 */ 
public function getCurrentCurrencySymbol()
{
  return $this->_priceCurrency->getCurrency()->getCurrencySymbol();
}
Run Code Online (Sandbox Code Playgroud)

另一种方法可能如下

protected $_localeCurrency;

protected $_storeManager;

public function __construct(
  \Magento\Backend\Block\Template\Context $context,
  \Magento\Framework\Locale\CurrencyInterface $localeCurrency,
  \Magento\Store\Model\StoreManagerInterface $storeManager,
  array $data = []
)
{           
  $this->_localeCurrency = $localeCurrency;
  $this->_storeManager = $storeManager;
  parent::__construct($context, $data);
}

/**
 * Get current currency symbol
 *
 * @return string
 */ 
public function getCurrentCurrencySymbol()
{
  $code = $this->_storeManager->getStore()->getCurrentCurrencyCode();
  return $this->_localeCurrency->getCurrency($code)->getSymbol();
}
Run Code Online (Sandbox Code Playgroud)