我正在自定义default.ctp
文件,我正在尝试在页面顶部显示当前登录的用户名。
在app_controller.php
中,我有以下内容:
function beforeFilter()
{
$user = $this->Auth->user();
if($user != null)
{
$this->Session->write('user_name',$user['User']['username']);
}
}
在default.ctp
,我有:
$user = $this->Session->read('Auth.User');
if(!empty($user))
{
echo 'Hello, ' . $user['user_name'];
}
但是,似乎值$user_name
未在任何地方设置。
我做错了什么?有没有更好的方法来实现这一目标?
更新:我已按照答案中的说明对其进行了修改,但仍然无效。我收到一个错误:
未定义索引:user_name [APP / views / layouts / default.ctp,第21行]
答案 0 :(得分:12)
您也可以直接在view / layout
中使用SessionHelper$user = $this->Session->read('Auth.User');
if(!empty($user)) {
echo 'Hi ', $user['user_name'];
}
答案 1 :(得分:-2)
$user = $this->Session->read('Auth.User');
if(count($user))
echo $user['name'];