摘要:通过自定义组件实现标签云功能。
1、创建自定义标签云组件目录结构
2、创建标签云自定义组件类
<?php namespace frontend\widgets\tags; /** * 标签云组件 */ use Yii; use yii\bootstrap\Widget; use yii\base\Object; use common\models\PostExtendsModel; use common\models\PostsModel; use yii\db\Query; use common\models\TagsModel; class TagsWidget extends Widget { public $title = ''; public $limit = 20; public function run() { $res = TagsModel::find() ->orderBy(['post_num'=>SORT_DESC]) ->limit($this->limit) ->all(); $result['title'] = $this->title?:'标签云'; $result['body'] = $res?:[]; return $this->render('index',['data'=>$result]); } }
3、标签云组件数据渲染
<?php use yii\helpers\Url; ?> <div class="panel-title box-title"> <span><strong><?=$data['title']?></strong></span> </div> <div class="panel-body padding-left-0"> <div class="tag-cloud"> <?php foreach ($data['body'] as $list):?> <a href="<?=Url::to(['posts/index','tag'=>$list['tag_name']])?>"><?=$list['tag_name']?></a> <?php endforeach;?> </div> </div>
4、首页调用标签云组件
<!--标签云--> <?= TagsWidget::widget()?>
标签云css样式:
/**/ .tag-cloud a { border: 1px solid #ebebeb; padding: 2px 7px; color: #333; line-height: 2em; display: inline-block; font-size:14px; margin: 0 7px 7px 0; transition: all 0.2s ease; } .tag-cloud a:hover { background-color:#5bc0de; text-decoration: none; }
标签云显示效果:
到此,网站前台基本完成。接下来就要完成后台的创建管理了。