11

如何在magento2中获取当前类别?

我想在自定义 phtml 文件中获取类别名称和类别 ID。

4

5 回答 5

23

以上似乎是正确的,但我认为直接跳转到注册表并不是最好的方法。Magento 提供了一个已经封装了该功能的层解析器。(参见目录插件中的 TopMenu 块)

我建议注入 \Magento\Catalog\Model\Layer\Resolver 类并使用它来获取当前类别。这是代码:

<?php

namespace FooBar\Demo\Block;

class Demo extends \Magento\Framework\View\Element\Template
{
    private $layerResolver;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\Layer\Resolver $layerResolver,
        array $data = []
    ) {
        parent::__construct($context, $data);

        $this->layerResolver = $layerResolver;
    }

    public function getCurrentCategory()
    {
        return $this->layerResolver->get()->getCurrentCategory();
    }
}

下面是实际的getCurrentCategory()方法在 Resolver 类中的作用。

public function getCurrentCategory()
{
    $category = $this->getData('current_category');
    if ($category === null) {
        $category = $this->registry->registry('current_category');
        if ($category) {
            $this->setData('current_category', $category);
        } else {
            $category = $this->categoryRepository->get($this->getCurrentStore()->getRootCategoryId());
            $this->setData('current_category', $category);
        }
    }

    return $category;
}

正如您所看到的,它仍然使用注册表,但它提供了一个回退,以防万一失败。

于 2017-09-25T21:59:14.843 回答
15

Magento 为正在访问的类别设置注册表。因此,要获取当前类别,请使用以下方法:

/**
 * @param \Magento\Framework\Registry $registry
 */

protected $_registry;

public function __construct(
    \Magento\Framework\Registry $registry
) {
    $this->_registry = $registry;
}

然后使用:

$category = $this->_registry->registry('current_category');//get current category

现在您可以访问集合并获取详细信息,例如$category->getName()

于 2017-01-31T05:52:48.600 回答
10

无需使用对象管理器或注入类。您可以通过以下方式使用内置帮助程序类Magento\Catalog\Helper\Data

<?php 
    $catalogHelperData = $this->helper('Magento\Catalog\Helper\Data');
    $categoryObject = $catalogHelperData->getCategory();
    $categoryId = $categoryObject->getId();
    $categoryName = $categoryObject->getName();
?>

此代码片段适用于与产品列表页面或产品详细信息页面相关的任何 phtml内置或自定义)文件。

于 2019-09-13T07:25:06.633 回答
10

试试这个代码。这肯定会帮助你。

<?php 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
    echo $category->getId();
    echo $category->getName();
?>
于 2016-01-20T04:57:49.063 回答
0

在 Category 页面的 *.phtml 文件中,可以使用以下代码段获取 Category 数据:

$currentCategory = $this->helper('Magento\Catalog\Helper\Data')->getCategory();
于 2021-10-15T19:32:50.030 回答