本文实例讲述了ThinkPHP中Widget扩展的两种写法及调用方法。分享给大家供大家参考,具体如下:
Widget扩展一般用于页面组件的扩展,在页面根据需要输出不同的内容,下面介绍一下ThinkPHP中Widget的两种写法及调用
写法一:
ArticlWidget.class.php文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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目录下
1
2
3
4
5
|
< 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 > |
写法二:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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文件夹下,则写法如下:
1
|
$this ->display(dirname( __FILE__ ) . '/Article/articleList.html' ); |
希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。