Yii2中定義自己的Widget


1. 調用Widget 

Php代碼,在需要調用的view層頁面中: 
1 <?=HotWidget::widget()?>


或者 將內容包含在H1標簽中,頁面中代碼為:

1 <?php
2    use frontend\widgets\hot\HotWidget;
3 ?>
4 <?php HotWidget::begin(); ?>
5    第一個Widget在H1標簽中
6 <?php HotWidget::end(); ?>

 

請注意,我們使用 ob_start()函數來緩沖輸出,對應的HotWidget中代碼為:

 1 <?php
 2    namespace frontend\widgets\hot;
 3    use yii\base\Widget;
 4    class HotWidget extends Widget {
 5       public function init() {
 6          parent::init();
 7          ob_start();
 8       }
 9       public function run() {
10          $content = ob_get_clean();
11          return "<h1>$content</h1>";
12       }
13    }
14 ?>  


也可以傳參到Widget類 

1 <?=PostWidget::widget(['limit' => 1, 'title' => 'More 文章'] );?>

參數limit , title 自動映射到Widget類的同名屬性,所以在定義Widget時,別忘記了聲明該屬性。 

2. 創建Widget 

  要創建一個窗口小部件,應該擴展類 yii\base\Widget或者是類yii\bootstrap\Widget。
  那么需要重寫 yii\base\Widget::init() 和 yii\base\Widget::run() 函數。
  run()函數將返回渲染的結果。
  init()函數將標准化小部件的屬性。

 
<?php

namespace frontend\widgets\post;

use yii\base\Widget;

class PostWidget extends Widget
{
    /**
     * [$title 文章列表]
     * @var string
     */
    public $title = '';
    /**
     * [$limit 顯示條數]
     * @var integer
     */
    public $limit = 6;
    
    public function run ()
    {
        
        return $this->render('index', ['data' => $result]);
    }
}

 

或者,同時包括init 和 run:

 1 <?php
 2 namespace frontend\widgets\banner;
 3 
 4 use Yii;
 5 use yii\bootstrap\Widget;
 6 
 7 class BannerWidget extends Widget
 8 {
 9     public $items = [];
10 
11     public function init()
12     {
13         parent::init();
14         ob_start();
15     }
16 
17     public function run()
18     {
19          $content = ob_get_clean();
20          return "<h1>$content</h1>";
21     }
22 }

 

要點
窗口小部件應該 -
要在MVC模式下創建。應該保持表現層在視圖,邏輯在窗口小部件(widget)類。
設計成自包含的。最終開發人員應該能夠將它設計到一個視圖。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM