How is it possible to output the current store name in a Magento 2 custom template with a custom block?
3 Answers
you need to use the instance of \Magento\Framework\App\Config\ScopeConfigInterface
in your block:
Create the method getStoreName()
public function getStoreName()
{
return $this->_scopeConfig->getValue(
'general/store_information/name',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
}
and call in your template echo $this->getStoreName()
-
Loos like a great solution, but I get the following error: Fatal error: Call to a member function dispatch() on a non-object in /vendor/magento/framework/View/Element/AbstractBlock.php on line 637. Commented Dec 14, 2015 at 9:36
-
-
1@Marius 's approach is right, but it didn't work for me. Instead I've used
\Magento\Store\Model\StoreManagerInterface $storeManager
in constructor andpublic function getStoreName() { return $this->storeManager->getStore()->getName(); }
Instead ofgetName()
you can usegetCode()
,getId()
.– RazvanCommented May 19, 2016 at 9:37
Use store manager, which holds information about active store. If custom block is not inherited from Template
block, inject dependency on \Magento\Store\Model\StoreManagerInterface
in construct.
<?php
namespace VendorName\ModuleName\Block;
class CustomBlock extends \Magento\Framework\View\Element\Template
{
/**
* Get current store name.
*
* @return string
*/
public function getCurrentStoreName()
{
return $this->_storeManager->getStore()->getName();
}
}
Then in template:
<?php
/**
* @var $block \VendorName\ModuleName\Block\CustomBlock
*/
echo "<h1>Current store name is '{$block->getCurrentStoreName()}'</h1>";
?>
-
Thanks for your solution, but I don't want to show the store view name.Searched for the store name of the configuration. Commented Dec 14, 2015 at 10:38
-
It always returns 'Default Store View' instead of my store name– coinhndpCommented Jul 28, 2020 at 10:52
To get a store configuration value like general/store_information/name
you can use the following
$config = new \Magento\Framework\App\Config\ScopeConfigInterface();
echo $config->getValue('general/store_information/name');
However, doing this from a block or helper would be cleaner. Below is a helper class that would exist in your own custom module
namespace [Namespace]\[Module]\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* Retrieve store name
*
* @return string|null
*/
public function getStoreName()
{
return $this->scopeConfig->getValue(
'general/store_information/name',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
}
}
Which you would inject as dependency in your block class