本书未发布

54. 头像显示

未匹配的标注

简介

本节里,我们将完成在用户个人中心和顶部导航显示用户头像功能。

需求分解

  • 已经上传头像的话,显示用户上传的图像;
  • 如果用户没有上传头像,显示系统默认头像;
  • 在显示头像时限制一下 标签大小,避免因为用户上传的头像图片太大造成页面样式乱掉。

数据模型

我们通过在用户模型里声明一个名为 getAvatarPathAttr 的 获取器 来实现当用户上传了头像图片时显示上传的头像图片,否则显示系统默认头像图片。

application/common/model/User.php

<?php
.
.
.
class User extends Model
{
    .
    .
    .
    /**
     * 用户头像路径
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-06-19
     * @return   [type]             [description]
     */
    public function getAvatarPathAttr()
    {
        if(empty($this->avatar)){
            return '/static/assets/index/images/default_avatar.png';
        }
        return $this->avatar;
    }
}

视图页面

  1. 在个人中心页面显示用户头像图片:

application/index/view/user/read.html

.
.
.
<div class="card">
    <img class="card-img-top" src="{$user->avatar_path}" width="200px" height="200px" alt="{{ $user->name }}">
    <h5><strong>个人简介</strong></h5>
    <p>{$user->introduction}</p>
    <hr>
    <h5><strong>注册于</strong></h5>
    <p>三天前</p>
</div>
.
.
.
  1. 在顶部导航栏显示用户头像:

application/index/view/layout/_header.html

.
.
.
<li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        <img src="{$current_user->avatar_path}" class="img-responsive img-circle" width="30px" height="30px">
        {$current_user.name}
    </a>
    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
        .
        .
        .
    </div>
</li>
.
.
.
  1. 上传默认头像图片

[点击下载]() 项目默认头像图片,另存为 public/static/assets/index/images/default_avatar.png

样式优化

效果展示

提交代码

下面把代码纳入到版本管理:

$ git add -A
$ git commit '上传头像'

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~