Magento2如何创建自定义变量以显示当前分类名称?
Magento2 实现CMS块中显示当前分类名称的自定义变量方法
你之前的尝试存在两个核心问题:
Mage::registry是Magento1的语法,Magento2已不再使用;- 自定义变量的HTML值字段仅支持静态内容,直接写后端逻辑或无效JS无法动态获取当前分类数据。
以下提供两种可行方案,按需选择:
方案一:扩展自定义变量实现动态取值
适合坚持使用{{customVar code=currentcategory}}指令的场景,需创建简单自定义模块:
1. 创建模块文件结构
在Magento根目录下创建以下文件:
app/code/YourName/CustomVariable/registration.php
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'YourName_CustomVariable', __DIR__ );
app/code/YourName/CustomVariable/etc/module.xml
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="YourName_CustomVariable" setup_version="1.0.0"> <sequence> <module name="Magento_Cms"/> </sequence> </module> </config>
app/code/YourName/CustomVariable/Model/Variable.php
<?php namespace YourName\CustomVariable\Model; use Magento\Cms\Model\Variable as CoreVariable; use Magento\Framework\Registry; class Variable extends CoreVariable { protected $registry; public function __construct( \Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, array $data = [] ) { $this->registry = $registry; parent::__construct($context, $resource, $resourceCollection, $data); } public function getHtmlValue() { if ($this->getCode() == 'currentcategory') { $currentCategory = $this->registry->registry('current_category'); return $currentCategory ? $currentCategory->getName() : ''; } return parent::getHtmlValue(); } }
2. 启用模块并更新系统
在Magento根目录执行以下命令(若为共享主机,可联系服务商操作):
bin/magento module:enable YourName_CustomVariable bin/magento setup:upgrade bin/magento setup:di:compile bin/magento cache:clean
3. 配置自定义变量
回到后台的内容 > 自定义变量,确保currentcategory变量存在,其HTML值字段可留空(模块逻辑会自动替换为当前分类名称)。
方案二:用Block指令替代(无需模块,更简单)
若无需坚持使用自定义变量语法,可直接在CMS块中使用以下代码:
More information about {{block class="Magento\Catalog\Block\Category\View" template="Magento_Catalog::current_category_name.phtml"}}
创建模板文件
在当前主题目录下创建模板文件:app/design/frontend/YourTheme/Magento_Catalog/templates/current_category_name.phtml,内容如下:
<?php $currentCategory = $block->getCurrentCategory(); if ($currentCategory) { echo $currentCategory->getName(); } ?>
最后清除后台缓存,访问分类页面即可看到效果。
内容的提问来源于stack exchange,提问作者bplet
相关产品推荐
相关产品推荐

