Magento 2: get the current currency code
Вопрос
In Magento 1, you could retrieve the current currency code by doing:
Mage::app()->getStore()->getCurrentCurrencyCode()
I'm wondering what is the recommended way of doing it in Magento 2. In my case in a block.
Решение
In a block
In Magento 2, you can use the \Magento\Store\Model\StoreManagerInterface
which is stored in an accessible variable $_storeManager
for every class extending \Magento\Framework\View\Element\Template
so most of the block classes (Template
, Messages
, Redirect
block types but not Text
nor TextList
).
This way in your block, you can directly type the following code to get the current currency code:
$this->_storeManager->getStore()->getCurrentCurrency()->getCode()
No need to inject the \Magento\Store\Model\StoreManagerInterface
in your construct as it's a variable accessible from any block class.
In any other class
You can inject the \Magento\Store\Model\StoreManagerInterface
in your constructor:
protected $_storeManager;
public function __construct(\Magento\Store\Model\StoreManagerInterface $storeManager)
{
$this->_storeManager = $storeManager;
}
Then call the same function as the block:
$this->_storeManager->getStore()->getCurrentCurrency()->getCode()
Другие советы
This takes inspiration from Magento\Framework\Pricing\Render\Amount
and it's working good in my case (behaving like Magento):
protected $_priceCurrency;
public function __construct(
...
\Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency,
...
)
{
$this->_priceCurrency = $priceCurrency;
...
}
/**
* Get current currency code
*
* @return string
*/
public function getCurrentCurrencyCode()
{
return $this->_priceCurrency->getCurrency()->getCurrencyCode();
}
You can get the currency symbol also:
/**
* Get current currency symbol
*
* @return string
*/
public function getCurrentCurrencySymbol()
{
return $this->_priceCurrency->getCurrency()->getCurrencySymbol();
}
expanding on the accepted answer if injecting the storemanagerinterface is not an option you can use the objectmanager like this:
/**
5 * Get Store Name
4 *
3 * @return \Magento\Sales\Model\StoreManagerInterface
2 */
1 protected function getStore() {
123 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
1 $storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
2 return $storeManager->getStore();
3 }
after which the currency can get fetched with $this->getStore()->getCurrentCurrency()->getCode();