What's the best method to get specific data in Magento 2, i.e. to list all the websites in the CMS? In Magento 1 I'd use


But that doesn't work in Mag2 anymore. I do see code like this:

$this->storeManager = $storeManager;
$id = $this->storeManager->getStore()->getId();

Which I guess would be a fair starting point, but whenever I call this code in the frontend, I get Notice: Undefined variable: storeManager errors. So appareantly this isn't the way to call that storeManager. My question is; what is the right way?

1 Answer 1


To get the list of all websites, you indeed need to use the storeManager, which is a native variable of every block extending \Magento\Framework\View\Element\Template:

In your block class, you either directly do:


Or if you need to get the websites in a template assigned to your block you can declare a function:

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

Then in your template you can do:


Note that if you want to get the websites in a controller or any other non block class, you will have to use dependency injection in the constructor first to be able to use the storeManager code above:

protected $_storeManager;

public function __construct(\Magento\Store\Model\StoreManagerInterface $storeManager)
    $this->_storeManager = $storeManager;
  • Bear with me here, so I need to make a custom module to use that storeManager var, just to list the websites in the frontend? Seems rather extensive.
    – Asitis
    Apr 4, 2016 at 9:10
  • When you say "list the websites in the frontend" what does that mean ? In a template ? On a CMS page ? Apr 4, 2016 at 9:11
  • I'm but a humble frontend developer, and Mag2 is quite new to me. All I want to do is to add a website switcher to the header, next to the language switcher. In Mag1 I'd just call the info using the Mage::app(); function. I guess what I'm looking for is the right workflow to get data like that in Magento2
    – Asitis
    Apr 4, 2016 at 9:13
  • 1
    Well there's already a store switcher provided with M2: Magento\Store\Block\Switcher with its corresponding template: Magento\Store\view\frontend\templates\switch\stores.phtml Apr 4, 2016 at 9:15
  • 1
    Well that's a whole another question to your OP, but I reckon you should keep an eye here: magento.stackexchange.com/questions/108851/… Apr 4, 2016 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.