Yii中自定义Widget

来源:互联网 发布:网络大电影的优势 编辑:程序博客网 时间:2024/06/05 01:10

先在protected目录下建立一个widget文件夹,保存widget:

建立BannerWidget.php文件,

class BannerWidget extends CWidget{    function run(){        echo CHtml::image('images/banner1.jpg');        //$this->render('index');//在protected/widget/views/index.php    }}

在views中引用:

$this->widget('application.widget.BannerWidget');

===========================================================================

下面以一个随机广告图片为例说明Yii中Widget的用法

1. 调用Widget

<?php $this->widget('WidgetName'); ?>

或者
<?php $widget=$this->beginWidget('path.to.WidgetClass'); ?>
...可能会由小物件获取的内容主体...

<?php $this->endWidget(); ?>

也可以传参到Widget类 

<?php $userId = 1; ?><?php $this->widget('WidgetName',array('userId'=>$userId)); ?>

参数userId自动映射到Widget类的同名属性,所以在定义Widget时,别忘记了声明该属性。 

2. 创建Widget

自定义Widget类要继承CWidget,覆盖方法run 

<?phpclass BannerMagic extends CWidget {    public function run(){    }}

或者: 

class MyWidget extends CWidget {    public function init() {        // 此方法会被 CController::beginWidget() 调用    }     public function run() {        // 此方法会被 CController::endWidget() 调用    }}

下面是是BannerMagicWidget实现 

<?php class BannerMagicWidget extends CWidget {   public function run() {     $random = rand(1,3);     if ($random == 1) {       $advert = "advert1.jpg";     }  else if ($random == 2) {       $advert = "advert2.jpg";     }  else {       $advert = "advert3.jpg";     }      $this->render('bannermagic',array(       "advert"=>$advert,     ));   }}

存储到protected\components\BannerMagicWidget.php 

对应的view文件可能的内容如下: 

<img src="images/adverts/<?php echo $advert; ?>" alt="whatever" />

存储到protected\components\views\bannermagic.php 

3. 调用该Widget

<?php $this->widget('BannerMagicWidget'); ?>












0 0