The question:
I’m trying to show a custom block for each store view / language.
Therefore I want to create switch statement like:
$lang = // Get language code or store view code here;
switch ($lang) {
case 'en':
// English block
break;
case 'nl':
// Dutch block
break;
default:
// Dutch block
break;
}
How can I get this? I need it in this file appdesignfrontendVenusthemefloristyVes_Themesettingstemplatesheaderdefault.phtml
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
You can use MagentoStoreApiDataStoreInterface
or MagentoFrameworkLocaleResolver
class to get store language.
- BY USING
MagentoStoreApiDataStoreInterface
CLASS
With Dependency Injection
protected $_store;
public function __construct(
...
MagentoStoreApiDataStoreInterface $store,
...
) {
...
$this->_store = $store;
...
}
Now use getLocaleCode()
to get language:
$currentStore = $this->_store->getLocaleCode();
if($currentStore == 'en_US'){
}
With objectManager
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$store = $objectManager->get('MagentoStoreApiDataStoreInterface');
echo $store->getLocaleCode();
- BY USING
MagentoFrameworkLocaleResolver
CLASS
With Dependency Injection
protected $_store;
public function __construct(
...
MagentoFrameworkLocaleResolver $store,
...
) {
...
$this->_store = $store;
...
}
Now use getLocale()
to get language:
$currentStore = $this->_store->getLocale();
if($currentStore == 'en_US'){
}
With objectManager
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$store = $objectManager->get('MagentoFrameworkLocaleResolver');
echo $store->getLocale();
NOTE: You should never use MagentoFrameworkAppObjectManager::getInstance()
It defeats the purpose of dependency injection.
Method 2
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 = MagentoFrameworkAppObjectManager::getInstance();
$getLocale = $objectManager->get('MagentoFrameworkLocaleResolver');
$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(
MagentoFrameworkLocaleResolver $locale
) {
$this->locale = $locale;
}
call inside phtml file,
$currentCode = $this->locale->getLocale();
$langCode = strstr($currentCode, '_', true);
if($langCode == 'en_US'){
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0