Yii2中定义自己的Widget

1. 调用Widget 

Php代码,在需要调用的view层页面中: 
1 <?=HotWidget::widget()?>


或者 将内容包含在H1标签中,页面中代码为:

1 <?php
2    use frontendwidgetshotHotWidget;
3 ?>
4 <?php HotWidget::begin(); ?>
5    第一个Widget在H1标签中
6 <?php HotWidget::end(); ?>

请注意,我们使用 ob_start()函数来缓冲输出,对应的HotWidget中代码为:

 1 <?php
 2    namespace frontendwidgetshot;
 3    use yiiaseWidget;
 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 

  要创建一个窗口小部件,应该扩展类 yiiaseWidget或者是类yiiootstrapWidget。
  那么需要重写 yiiaseWidget::init() 和 yiiaseWidget::run() 函数。
  run()函数将返回渲染的结果。
  init()函数将标准化小部件的属性。

 
<?php

namespace frontendwidgetspost;

use yiiaseWidget;

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 frontendwidgetsanner;
 3 
 4 use Yii;
 5 use yiiootstrapWidget;
 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)类。
设计成自包含的。最终开发人员应该能够将它设计到一个视图。

 
原文地址:https://www.cnblogs.com/yunyunde/p/7126337.html