如何在PrestaShop 1.7中用registerHook('customerAccount')及displayCustomerAccount显示账户信息
嘿,我来帮你搞定在PrestaShop 1.7的「我的账户」页面添加自定义内容的问题!咱们分两部分讲,先搞懂registerHook('customerAccount')和displayCustomerAccount的用法,再落地你的需求。
1. 关于
registerHook('customerAccount') 这个钩子主要用来在客户账户的左侧导航菜单里添加自定义菜单项,不是直接在页面主体显示内容。要使用它,你需要在模块里完成两步:
注册钩子
在你的模块类里,有两种方式注册:
// 方式1:在install()方法中注册 public function install() { return parent::install() && $this->registerHook('customerAccount'); } // 方式2:在getHooks()方法中声明(PrestaShop 1.7+推荐,更规范) public function getHooks() { return [ 'customerAccount', // 这里可以加其他你需要的钩子 ]; }
实现钩子方法
注册后,要写对应的钩子方法hookCustomerAccount(),返回菜单项的HTML:
public function hookCustomerAccount() { // 调用模板文件渲染菜单项 return $this->context->smarty->fetch($this->getLocalPath() . 'views/templates/hook/customer-account-link.tpl'); }
对应的模板文件customer-account-link.tpl可以这么写:
<li> <a href="{$link->getModuleLink('你的模块名称', '自定义控制器')}" title="我的自定义页面"> {l s='我的自定义页面' mod='你的模块名称'} </a> </li>
2. 使用
displayCustomerAccount在「我的账户」页面展示自定义信息 如果你的需求是直接在/index.php?controller=my-account的页面主体区域显示内容,那displayCustomerAccount才是你要找的钩子。
注册displayCustomerAccount钩子
同样先在模块里注册这个钩子:
// 在install()方法中注册 public function install() { return parent::install() && $this->registerHook('displayCustomerAccount'); } // 或者在getHooks()中声明 public function getHooks() { return [ 'displayCustomerAccount', // 其他钩子... ]; }
实现钩子方法
接着写hookDisplayCustomerAccount()方法,返回你要展示的自定义内容:
public function hookDisplayCustomerAccount() { // 准备自定义数据,比如从数据库取用户专属信息 $customData = [ 'user_name' => $this->context->customer->firstname, 'custom_notice' => '欢迎回来!这是为你准备的专属提示~' ]; // 把数据传给模板 $this->context->smarty->assign($customData); // 返回渲染后的模板内容 return $this->context->smarty->fetch($this->getLocalPath() . 'views/templates/hook/display-customer-account.tpl'); }
对应的模板文件display-customer-account.tpl内容示例:
<div class="custom-account-section"> <h3>{l s='我的专属信息' mod='你的模块名称'}</h3> <p>你好,{$user_name}!{$custom_notice}</p> <p>这里可以添加更多自定义内容,比如积分、订单统计等</p> </div>
3. 验证效果
完成以上步骤后,安装你的模块,登录前台账号进入「我的账户」页面,就能看到你添加的自定义内容了(默认主题下会显示在账户内容区域的顶部,具体位置取决于你使用的主题钩子布局)。
内容的提问来源于stack exchange,提问作者Gagandeep Singh
相关产品推荐
相关产品推荐

