这篇文章主要介绍了ThinkPHP中Widget扩展的两种写法及调用方法,详细分析了Widget扩展的写法及相应的调用技巧,需要的朋友可以参考下

Widget扩展一般用于页面组件的扩展,在页面根据需要输出不同的内容,下面介绍一下ThinkPHP中Widget的两种写法及调用

写法一:

ArticlWidget.class.php文件:

class ArticleWidget extends Widget { /** * * @param array $data * @return type * 调用方法:{:W('ArticleList',array('cid'=>25,'limit'=>5))} * cid为分类id,limit为调用数量 */ public function render($data) { $Article = M('Article'); $articleMap["cid"] = $data["cid"]; $data["articleList"] = $Article->where($articleMap)->order('id desc')->limit($data["limit"])->select(); foreach ($articleList as $key => $value) { if ($value["thumbnail"] == "") { $data["articleList"][$key]["thumbnail"] = '/Public/Img/Common/noThumbnail.jpg'; } } return $this->renderFile('articleList', $data); } }

模板文件articleList.html在Lib/Widget/Article目录下

<volist name="articleList" id="articleList_vo"> <li> <a href="__APP__/Channel/articleDetail/code/article/id/{$articleList_vo.id}" rel="external nofollow" title="{$articleList_vo.title}">{$articleList_vo.title}</a> </li> </volist>

写法二:

class ArticleWidget extends Action { /** * * @param array $data * @return type * 调用方法:{:R('Article/articleList',array('cid'=>25,'limit'=>5),'Widget')} * cid为分类id,limit为调用数量 */ public function articleList($cid, $limit) { $Article = M('Article'); $articleMap["cid"] = $cid; $data = $Article->where($articleMap)->order('id desc')->limit($limit)->select(); foreach ($data as $key => $value) { if ($value["thumbnail"] == "") { $data[$key]["thumbnail"] = '/Public/Img/Common/noThumbnail.jpg'; } } $this->assign('articleList', $data); $this->display('Widget:articleList'); } }

模板文件articleList.html,内容同写法一,但放在Tpl/风格名/Widget/目录下

如果模板文件放在ArticleWiget.class.php文件所在目录的Article文件夹下,则写法如下:

$this->display(dirname(__FILE__) . '/Article/articleList.html');相关推荐:

PHP预定义变量9大超全局数组用法详解_php基础

PHP 随机数 C扩展随机数

理解php依赖注入和控制反转_php技巧