如何在magento2中获取当前类别?
我想在自定义 phtml 文件中获取类别名称和类别 ID。
以上似乎是正确的,但我认为直接跳转到注册表并不是最好的方法。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;
}
正如您所看到的,它仍然使用注册表,但它提供了一个回退,以防万一失败。
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()
无需使用对象管理器或注入类。您可以通过以下方式使用内置帮助程序类Magento\Catalog\Helper\Data
。
<?php
$catalogHelperData = $this->helper('Magento\Catalog\Helper\Data');
$categoryObject = $catalogHelperData->getCategory();
$categoryId = $categoryObject->getId();
$categoryName = $categoryObject->getName();
?>
此代码片段适用于与产品列表页面或产品详细信息页面相关的任何 phtml(内置或自定义)文件。
试试这个代码。这肯定会帮助你。
<?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();
?>
在 Category 页面的 *.phtml 文件中,可以使用以下代码段获取 Category 数据:
$currentCategory = $this->helper('Magento\Catalog\Helper\Data')->getCategory();