1. Call widgets
The code is as follows: |
Copy code |
<? Php $ this-> widget ('widgetname');?> |
Or
The code is as follows: |
Copy code |
<? Php $ widget = $ this-> beginWidget ('path. to. Widgetclass');?> |
... Content subject that may be obtained by small objects...
The code is as follows: |
Copy code |
<? Php $ this-> endWidget ();?> |
You can also pass parameters to the Widget class.
The code is as follows: |
Copy code |
<? Php $ userId = 1;?> <? Php $ this-> widget ('widgetname', array ('userid' => $ userId);?>
|
The userId parameter is automatically mapped to the same name property of the Widget class. Therefore, when defining a Widget, do not forget to declare this property.
2. Create a Widget
The custom Widget class inherits the CWidget and overwrites the run method.
The code is as follows: |
Copy code |
<? Php Class BannerMagic extends CWidget { Public function run (){ } }
|
Or:
The code is as follows: |
Copy code |
Class MyWidget extends CWidget { Public function init (){ // This method will be called by CController: beginWidget () } Public function run (){ // This method will be called by CController: endWidget () } }
|
The following is the implementation of BannerMagicWidget.
The code is as follows: |
Copy code |
<? 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, )); } }
|
Stored in protectedcomponentsBannerMagicWidget. php
The possible contents of the corresponding view file are as follows:
The code is as follows: |
Copy code |
"Alt =" whatever "/> |
Storage to protectedcomponentsviewsbannermagic. php
3. Call this Widget
The code is as follows: |
Copy code |
<? Php $ this-> widget ('bannermagicwidget ');?> |