【问题标题】:Get Category Name for specified Category id in phtml template - Magento2在phtml模板中获取指定类别ID的类别名称 - Magento2
【发布时间】:2016-12-03 00:47:21
【问题描述】:

你好,我是 magento2 的新手

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

提前致谢

【问题讨论】:

    标签: magento2


    【解决方案1】:

    你不应该使用ObjectManager

    你可以把这个放到Block里面,然后在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;
        }
    }
    

    【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 你不应该使用对象管理器,尝试使用下面的答案。
    猜你喜欢
    • 2017-12-24
    • 2017-08-02
    • 1970-01-01
    • 2021-10-16
    • 2013-05-21
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多