Magento 2: How to get current language of store?
You can use \Magento\Store\Api\Data\StoreInterface
or Magento\Framework\Locale\Resolver
class to get store language.
- BY USING
\Magento\Store\Api\Data\StoreInterface
CLASS
With Dependency Injection
protected $_store;
public function __construct(
...
\Magento\Store\Api\Data\StoreInterface $store,
...
) {
...
$this->_store = $store;
...
}
Now use getLocaleCode()
to get language:
$currentStore = $this->_store->getLocaleCode();
if($currentStore == 'en_US'){
}
With objectManager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$store = $objectManager->get('Magento\Store\Api\Data\StoreInterface');
echo $store->getLocaleCode();
- BY USING
Magento\Framework\Locale\Resolver
CLASS
With Dependency Injection
protected $_store;
public function __construct(
...
Magento\Framework\Locale\Resolver $store,
...
) {
...
$this->_store = $store;
...
}
Now use getLocale()
to get language:
$currentStore = $this->_store->getLocale();
if($currentStore == 'en_US'){
}
With objectManager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$store = $objectManager->get('Magento\Framework\Locale\Resolver');
echo $store->getLocale();
NOTE: You should never use \Magento\Framework\App\ObjectManager::getInstance()
It defeats the purpose of dependency injection.
You can get current locale by using below way,
Use of Directly Objectmanager in phtml file is not perfect way for magento 2 standard,
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$getLocale = $objectManager->get('Magento\Framework\Locale\Resolver');
$haystack = $getLocale->getLocale();
$lang = strstr($haystack, '_', true);
switch ($lang) {
case 'en':
// English block
break;
case 'nl':
// Dutch block
break;
default:
// Dutch block
break;
}
You can call Block file and set one function for your requirement and call those function inside phtml file.
public function __construct(
\Magento\Framework\Locale\Resolver $locale
) {
$this->locale = $locale;
}
call inside phtml file,
$currentCode = $this->locale->getLocale();
$langCode = strstr($currentCode, '_', true);
if($langCode == 'en_US'){
}