You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PrestaShop 1.7在ps_categorytree外展示分类时link未定义如何赋值

问题原因

PrestaShop 1.7 中Category::getNestedCategories()方法返回的分类数组默认不会自带link属性,所以直接在模板调用{$mainCategory.link}就会报未定义索引的错误。

修复步骤

1. 修改模块PHP代码,批量生成分类链接

你需要遍历拿到的嵌套分类数组,调用PrestaShop自带的Link类为每个分类生成访问链接,修改后的PHP代码如下:

// 先获取嵌套分类数据
$allCategories = Category::getNestedCategories(null, $this->context->language->id);
// 实例化链接处理类
$link = $this->context->link;

// 递归处理所有分类,添加link属性
$addCategoryLink = function($categories) use (&$addCategoryLink, $link) {
    foreach ($categories as &$cat) {
        // 生成当前分类链接
        $cat['link'] = $link->getCategoryLink($cat['id_category']);
        // 递归处理子分类
        if (!empty($cat['children'])) {
            $cat['children'] = $addCategoryLink($cat['children']);
        }
    }
    return $categories;
};

// 处理分类数据
$allCategories = $addCategoryLink($allCategories);
// 赋值给smarty
$this->context->smarty->assign('allCategories', $allCategories);

return $this->fetch('module:'.$this->name.'/views/templates/widget/block.tpl');

2. 模板代码无需调整

你原来编写的tpl代码可以直接沿用,现在$mainCategory.link和$subCategory.link已经被正确赋值,不会再报索引未定义的错误。

补充说明

如果你的站点只需要处理一级和二级分类,不需要适配更深层级的分类,也可以不用递归函数,直接写双层循环赋值即可,逻辑和上述递归处理完全一致。

内容的提问来源于stack exchange,提问作者edwaan34

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 21:57:00