杉哥的个人博客

Thinkphp5 的widget(小部件)功能使用

现在Widget叫分层控制器,不过我习惯叫它小部件,它是非常好用的一个东西。网页上很多地方是可以公用的,比如说导航栏、用户登录区域等,我们可以使用小部件功能减少重复代码。

官方文档连接:https://www.kancloud.cn/manual/thinkphp5_1/353983

首先在模块下(比如前台index)建立一个widget文件夹。

新建控制器Widgets如下:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/8/8
* Time: 15:58
*/
namespace app\index\widget;
use think\Controller;
class Widgets extends Controller
{
/**
* 头部
* @return mixed
*/
public function head()
{
$carModel=model('Car');
$userId = session('id');
$carSum=$carModel->where('user_id','=',$userId)->count();
$goods=$carModel->where('user_id','=',$userId)->order('created_at')->limit(5)->select();
$this->assign('goods',$goods);
$this->assign('carSum', $carSum);
return $this->fetch('public/head');
}
//省略部分代码
}
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/8/8 * Time: 15:58 */ namespace app\index\widget; use think\Controller; class Widgets extends Controller { /** * 头部 * @return mixed */ public function head() { $carModel=model('Car'); $userId = session('id'); $carSum=$carModel->where('user_id','=',$userId)->count(); $goods=$carModel->where('user_id','=',$userId)->order('created_at')->limit(5)->select(); $this->assign('goods',$goods); $this->assign('carSum', $carSum); return $this->fetch('public/head'); } //省略部分代码 }
<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/8
 * Time: 15:58
 */

namespace app\index\widget;

use think\Controller;

class Widgets extends Controller
{
    /**
     * 头部
     * @return mixed
     */
    public function head()
    {
        $carModel=model('Car');
        $userId = session('id');
        $carSum=$carModel->where('user_id','=',$userId)->count();
        $goods=$carModel->where('user_id','=',$userId)->order('created_at')->limit(5)->select();
        $this->assign('goods',$goods);
        $this->assign('carSum', $carSum);
        return $this->fetch('public/head');
    }
//省略部分代码
}
在index/view/public目录下:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!-- 头部 -->
<div class="hsh_head_top">
<div class="hsh_head_t">
<div class="hsh_head_t_l">
<span class="hsh_mr35">欢迎来到好森活网上药店!</span>
<!-- 省略部分代码 -->
<!-- 头部 --> <div class="hsh_head_top"> <div class="hsh_head_t"> <div class="hsh_head_t_l"> <span class="hsh_mr35">欢迎来到好森活网上药店!</span> <!-- 省略部分代码 -->
<!-- 头部 -->
<div class="hsh_head_top">
    <div class="hsh_head_t">
        <div class="hsh_head_t_l">
            <span class="hsh_mr35">欢迎来到好森活网上药店!</span>
<!-- 省略部分代码 -->

最后就是调用了,在需要的模板页面直接加载输出就行。