OpenCart仅支持展示2级分类,求生成完整UL-LI分类树的类
解决OpenCart生成完整多级分类树的问题
首先得说,OpenCart默认确实只处理到2级分类,但咱们完全不需要额外找什么现成类,靠递归就能轻松实现无限级的分类树,直接基于现有model_catalog_category模型扩展就行。
方法一:用递归函数获取全层级分类数据
你可以在控制器里(比如catalog/controller/common/sidebar.php,或者自定义的控制器)加个递归函数,用来遍历所有层级的分类:
// 递归获取分类及其所有子分类 function buildCategoryTree($parent_id = 0) { $category_data = []; // 调用OpenCart自带的模型方法获取当前父分类下的子分类 $categories = $this->model_catalog_category->getCategories($parent_id); foreach ($categories as $category) { // 递归调用,获取当前分类的子分类 $children = $this->buildCategoryTree($category['category_id']); $category_data[] = [ 'category_id' => $category['category_id'], 'name' => $category['name'], 'href' => $this->url->link('product/category', 'path=' . $category['category_id']), 'children' => $children ]; } return $category_data; }
然后在控制器的index方法里调用这个函数,拿到完整的分类树数据:
$this->load->model('catalog/category'); // 获取根分类(parent_id=0)下的全层级分类树 $category_tree = $this->buildCategoryTree(0); // 把数据传给视图层 $this->data['categories'] = $category_tree;
方法二:在视图里递归渲染UL-LI结构
接下来在对应的视图文件(比如catalog/view/theme/你的主题/template/common/sidebar.tpl)里,用递归的模板片段来渲染分类树:
先创建一个可复用的模板片段(比如category_tree.tpl):
<ul> <?php foreach ($categories as $category) { ?> <li> <a href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?></a> <?php // 如果当前分类有子分类,就递归加载模板片段 ?> <?php if (!empty($category['children'])) { ?> <?php // 把当前分类的子分类传给模板片段 $child_data['categories'] = $category['children']; echo $this->load->view($this->config->get('config_template') . '/template/common/category_tree.tpl', $child_data); ?> <?php } ?> </li> <?php } ?> </ul>
然后在主视图里引入这个片段,传入根分类数据:
<?php if (!empty($categories)) { ?> <?php echo $this->load->view($this->config->get('config_template') . '/template/common/category_tree.tpl', $this->data); ?> <?php } ?>
可选优化:限制最大展示层级
如果不想展示无限级,想限制最大层级(比如最多4级),可以给递归函数加个层级参数:
function buildCategoryTree($parent_id = 0, $current_level = 1, $max_level = 4) { // 当前层级超过限制,直接返回空数组 if ($current_level > $max_level) { return []; } $category_data = []; $categories = $this->model_catalog_category->getCategories($parent_id); foreach ($categories as $category) { // 递归时层级+1 $children = $this->buildCategoryTree($category['category_id'], $current_level + 1, $max_level); $category_data[] = [ 'category_id' => $category['category_id'], 'name' => $category['name'], 'href' => $this->url->link('product/category', 'path=' . $category['category_id']), 'children' => $children ]; } return $category_data; }
要是你用的是OpenCart 3.x版本,模板语法会换成Twig的{{ }},只需要把视图部分的代码对应调整就行,核心逻辑是一样的。这样就能实现像osCommerce那样的完整侧边分类树了。
内容的提问来源于stack exchange,提问作者limit
相关产品推荐
相关产品推荐

