Man*_*rla 19
你永远不应该使用ObjectManager.
你可以将它放在Block中,并getCategoryName()在phtml中调用该函数:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
Emi*_*ech 10
尝试使用以下代码获取Magento2中的Category对象:
$categoryId = 3;
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $_objectManager->create('Magento\Catalog\Model\Category')
->load($categoryId);
echo $category->getName();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18093 次 |
| 最近记录: |