【发布时间】:2016-04-25 19:33:17
【问题描述】:
如何在 magento2 中获取当前类别?
我想在自定义 phtml 文件中获取类别名称和类别 ID。
【问题讨论】:
-
这里的大多数答案都使用
Registry类,该类已被弃用一段时间。有没有办法不用Registry?
标签: magento2 magento-2.0
如何在 magento2 中获取当前类别?
我想在自定义 phtml 文件中获取类别名称和类别 ID。
【问题讨论】:
Registry 类,该类已被弃用一段时间。有没有办法不用Registry?
标签: magento2 magento-2.0
在Category页面的*.phtml文件中可以通过sn-p获取Category数据:
$currentCategory = $this->helper('Magento\Catalog\Helper\Data')->getCategory();
【讨论】:
上面看起来是正确的,但我认为直接跳转到注册表不是最好的方法。 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\Catalog\Helper\Data。
<?php
$catalogHelperData = $this->helper('Magento\Catalog\Helper\Data');
$categoryObject = $catalogHelperData->getCategory();
$categoryId = $categoryObject->getId();
$categoryName = $categoryObject->getName();
?>
此代码 sn-p 应适用于与产品列表页面或产品详细信息页面相关的任何 phtml(内置或自定义)文件。
【讨论】:
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()
【讨论】:
ObjectManager 是不好的做法
试试这个代码。这肯定会对你有所帮助。
<?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();
?>
【讨论】: