Magento2 : Get List of All Websites On Frontend

 

To get the list of all websites on frontend, we can use the storeManager variable, which is an in-built protected variable of every block extending MagentoFrameworkViewElementTemplate.
1) Calling in Block class file:

In our block class, we can directly get all websites by following code line:

$this->_storeManager->getWebsites();

If we want to call this in block template, simply create a method(function) and write like below:

public function getWebsites() {
$this->_storeManager->getWebsites();
}

Then call this method in your template as given below:

$block->getWebsites();

2) Calling in non-block class file:

If we want to get all websites in a controller or any other non-block class, we need to use dependency injection (DI) in the constructor to be able to use the storeManager code like above in block method we declared:

protected $_storeManager;

public function __construct(MagentoStoreModelStoreManagerInterface $storeManager)
{
$this->_storeManager = $storeManager;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s