当前位置: 技术文章>> 如何在Magento 2中获取当前类别

文章标题:如何在Magento 2中获取当前类别
  • 文章分类: Magento
  • 13116 阅读
系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》

本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。


在Magento2中获取当前类别的步骤:

步骤1:首先要获取当前类别,我们需要在自定义扩展名上创建一个块文件

在以下路径中添加Blockname.php

app\code\Vendor\Extension\Block\Blockname.php

现在添加以下代码

<?php
namespace Vendor\Extension\Block;
 
use Magento\Framework\View\Element\Template;
 
class Blockname extends Template
{
 
    protected $_registry;
 
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
    )
    {
        $this->_registry = $registry;
        parent::__construct($context);
    }
 
    public function getCurrentCategory()
    {
        return $this->_registry->registry('current_category');
    }
}

步骤2:现在我们将在模板phtml文件中获取当前类别

if ($currentCategory = $block->getCurrentCategory()) {
    echo $currentCategory->getName() . '<br />';
    echo $currentCategory->getUrl() . '<br />';
}

结语:

希望在上图的帮助下,所有人都能够在Magento 2中获得当前的类别信息。


推荐文章