Magento 2获取网站

4

我正在尝试在自定义模板中使用所有网站。 我已经在我的块中创建了以下内容;

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

我正在试图使用以下代码循环遍历我的模板中的网站;
<?php foreach ($block->getWebsites() as $website): ?>

当页面尝试加载时,我收到以下警告信息:
警告:foreach()的参数无效
我已经尝试了各种可能的变体,但似乎无法使其工作。在许多论坛上都引用了这种方法作为检索所有网站的正确方式,但对于我来说却不起作用。
如何在我的模板中获取一个网站数组?

尝试使用 print_r($block->getWebsites()) 查看其中的内容。 - DocRattie
有时候在调用其他函数时,我会遇到一些错误。所以你可以尝试这样写:$websites = $block->getWebsites(); foreach($websites as $website): - Master DJon
将以下内容添加到我的模板中(在<li>标签之间); <?php print_r($block->getWebsites()); ?> 我没有得到任何输出,只有一个空格在<li>中。 - ScorpioTiger
也尝试了这个; <?php $websites = $block->getWebsites(); ?> <?php foreach($websites as $website): ?> <?php endforeach; ?> 我得到了相同的错误; 为foreach()提供的参数无效。 - ScorpioTiger
请您可以发布您的代码块文件吗? - Emipro Technologies Pvt. Ltd.
1个回答

3
protected $_storeRepository;

public function __construct(
    \Magento\Framework\App\Helper\Context $context,
    \Magento\Store\Model\StoreRepository $StoreRepository
) {
    parent::__construct($context);
    $this->_storeRepository = $StoreRepository;
}

public function getWebsite()
{
    $stores = $this->_storeRepository->getList();
    $websiteIds = array();
    foreach ($stores as $store) {
        $websiteId = $store["website_id"];
        array_push($websiteIds, $websiteId);
    }

    return $websiteIds;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接