Trong Magento 1, bạn có thể truy xuất mã tiền tệ hiện tại bằng cách thực hiện:
Mage::app()->getStore()->getCurrentCurrencyCode()
Tôi đang tự hỏi cách làm được đề xuất trong Magento 2. Trong trường hợp của tôi là một khối.
Trong Magento 1, bạn có thể truy xuất mã tiền tệ hiện tại bằng cách thực hiện:
Mage::app()->getStore()->getCurrentCurrencyCode()
Tôi đang tự hỏi cách làm được đề xuất trong Magento 2. Trong trường hợp của tôi là một khối.
Câu trả lời:
Trong Magento 2, bạn có thể sử dụng \Magento\Store\Model\StoreManagerInterfaceđược lưu trữ trong một biến truy cập $_storeManagercho mỗi lớp kéo dài \Magento\Framework\View\Element\Templatenên hầu hết các lớp khối ( Template, Messages, Redirectloại khối nhưng không Textcũng không TextList).
Bằng cách này trong khối của bạn, bạn có thể nhập trực tiếp mã sau đây để lấy mã tiền tệ hiện tại:
$this->_storeManager->getStore()->getCurrentCurrency()->getCode()
Không cần phải tiêm \Magento\Store\Model\StoreManagerInterfacevào cấu trúc của bạn vì đây là một biến có thể truy cập được từ bất kỳ lớp khối nào.
Bạn có thể tiêm \Magento\Store\Model\StoreManagerInterfacetrong hàm tạo của bạn:
protected $_storeManager;
public function __construct(\Magento\Store\Model\StoreManagerInterface $storeManager)
{
$this->_storeManager = $storeManager;
}
Sau đó gọi hàm tương tự như khối:
$this->_storeManager->getStore()->getCurrentCurrency()->getCode()
Điều này lấy cảm hứng từ Magento\Framework\Pricing\Render\Amountvà nó hoạt động tốt trong trường hợp của tôi (hành xử như 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();
}
Bạn cũng có thể lấy ký hiệu tiền tệ:
/**
* Get current currency symbol
*
* @return string
*/
public function getCurrentCurrencySymbol()
{
return $this->_priceCurrency->getCurrency()->getCurrencySymbol();
}