当我们在多个视图页面中用到同一段动态的代码块时,我们就有必要用到thinkphp的widget扩展。
widget就相当于在页面中调用一个专属widget的控制器,并将它关联的视图植入当前的页面中,所以,widget的视图内容要按照当前页面的情况来考虑。
先来举个例子吧
需求:写一个供页面使用的主题widget,及多个页面要从数据库中提取所有主题并以列表的模式罗列在页面中,实现以主题筛选的功能。
应用页面:
<!-- 主题 -->
<dt class="filter_cat">主题:</dt>
{:W('Common/Subject/index')}
</dl>
这就是widget的应用方式,有参数的形式为
{:W('Common/Subject/index',array('id'=>$id)}
所以他就相当于访问subject控制器里的index方法,但是他的定义与控制器有所不同
定义widget的控制器,在与controller文件夹同路径下的widget文件夹中定义一个文件
SubjectWidget.class.php
<span style="font-size:18px;"><?php
namespace Common\Widget;
use Think\Controller;
class SubjectWidget extends Controller {
public function index($language_id=1){
//主题
$subject_lists = get_result(D('Common/CategoryView'),array('status'=>1,'type'=>'subject','language_id'=>$language_id));
$this->assign('subject_lists',$subject_lists);
$this->display(T('Common@Widget/Subject/index'));
}
}</span>
index.html
<?php
$options_arr=array_merge(I('get.'),array('subject'=>''));
$href=U('',$options_arr);
?>
<dd class="filter_con">
<ul>
<li class="item" ><a <?php if(!I('get.subject')){ ?>class="cur"<?php } ?> href="<?=$href?>"> 全部</a></li>
<?php
$options_arr=I('get.');
unset($options_arr['subject']);
foreach ($subject_lists as $val) {
$options_arr=array_merge(I('get.'),array('subject'=>$val['description_id']));
$href=U('',$options_arr);
?>
<li class="item" ><a <?php if(I('get.subject')==$val['description_id']){ ?>class="cur"<?php } ?> href="<?=$href?>"><?=$val['title']?></a></li>
<?php } ?>
</dd>
如上所示,这就是正真显示在主页面的东西,并且该页面的所有类都是主页面上定义或引用的,如果在里面写相对的url如U('')表示的是主界面所属的当前控制器下的当前方法,并非是widget的控制器或方法,所以,从这可以看出widget是完全服务于调用界面的