Yii create widget

Keywords: PHP

In Yii, we can inherit the yiibaseWidget class and override the yiibaseWidget::init() and / or yiibaseWidget::run() methods to create a widget

In general, the init method is used to process the properties of the widget, and the run method is used to process the code that the widget generates the rendering result. The rendering result in run can be output directly or returned as a string or put the widget content into the view file

One: using widget method

1: widget creation

<?php
/**
 * author: wangjian
 * date: 2019/12/13
 */
namespace frontend\widget;

use frontend\assets\AppAsset;
use yii\base\Widget;
use yii\helpers\Html;
class TestWidget extends Widget
{
    public $message;
    public function init()
    {
        if ($this->message == null) {
            $this->message = 'hello world!';
        }
    }
    public function run()
    {
        $messge = Html::encode($this->message);
        $html = <<<HTML
            <div class="test">
            {$messge}
            </div>
HTML;

        $js =<<<JS
            console.log(1);
JS;

        $this->view->registerJs($js);//

        $css = <<<CSS
        .test {
            color: #ac2925;
        }
CSS;
        $this->view->registerCss($css);
        AppAsset::register($this->view);//Register resource pack
        return $html;
    }
}

A widget is created as above

Sometimes there may be more content to render in the widget. At this time, we can use the yiibaseWidget::render() method to render the view file

public function run()
{
    return $this->render('index', [
        'message' => $this->message
    ]);
}

2: introduce the widget into the file in the re view

<?= \frontend\widget\TestWidget::widget(['message' => 'nihao']) ?>

Two: using begin() and end() methods

1: widget creation

<?php
/**
 * author: wangjian
 * date: 2019/12/13
 */
namespace frontend\widget;
use yii\base\Widget;
use yii\helpers\Html;
class TestBeginWidget extends Widget
{
    public $url;
    public function init()
    {
        parent::init();
        if ($this->url == null) {
            $this->url = 'http://www.baidu.com';
        }
        ob_start();//Turn on output cache
    }
    public function run()
    {
        $html = Html::beginTag('a', ['href' => $this->url]);
        $content = ob_get_clean();//Get output cache content
        $html .= $content;
        $html .= Html::endTag('a');
        return $html;
    }
}

2: widget use

<?php \frontend\widget\TestBeginWidget::begin(['url' => 'http://www.wj0511.com']); ?>
    Jump
<?php \frontend\widget\TestBeginWidget::end(); ?>

Posted by billli on Fri, 13 Dec 2019 11:50:46 -0800