获取 phtml 模板中指定类别 ID 的类别名称 - Magento2

Get Category Name for specified Category id in phtml template - Magento2

你好,我是 magento2 的新手

我想从指定的类别id中获取类别名称 有人可以帮忙吗?

提前致谢

尝试使用以下代码在 Magento2 中获取类别对象:

$categoryId = 3;
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $_objectManager->create('Magento\Catalog\Model\Category')
->load($categoryId);
echo $category->getName();

你永远不应该使用 ObjectManager

你可以把它放在块中,然后在 phtml 中调用函数 getCategoryName() :

namespace Company\Module\Block;

class CustomBlock extends \Magento\Framework\View\Element\Template 
{
    protected $_categoryFactory;    

    public function __construct(
    \Magento\Catalog\Model\CategoryFactory $categoryFactory,
    \Magento\Framework\View\Element\Template\Context $context,
    ) {
        $this->_categoryFactory = $categoryFactory;
        parent::__construct($context);
    }

    public function getCategoryName()
    {
        $categoryId = '43';
        $category = $this->_categoryFactory->create()->load($categoryId);
        $categoryName = $category->getName();
        return $categoryName;
    }
}