-
Notifications
You must be signed in to change notification settings - Fork 0
/
JSRegister.php
46 lines (35 loc) · 1.01 KB
/
JSRegister.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
namespace richardfan\widget;
use yii\base\Widget;
use yii\web\View;
/**
* Widget for registering script from view file
*
* Getting script in between this widget and register it by \yii\web\View::registerJs()
*/
class JSRegister extends Widget {
//variables to be passed to \yii\base\View::registerScript()
public $key = null;
public $position = View::POS_READY;
/**
* Start widget by calling ob_start(), caching all output to output buffer
* @see \yii\base\Widget::begin()
*/
public static function begin($config = []){
$widget = parent::begin($config);
ob_start();
return $widget;
}
/**
* Get script from output buffer, and register by \yii\web\View::registerJs()
* @see \yii\base\Widget::end()
*/
public static function end(){
$script = ob_get_clean();
$widget = parent::end();
if(preg_match("/^\\s*\\<script\\>(.*)\\<\\/script\\>\\s*$/s", $script, $matches)){
$script = $matches[1];
}
$widget->view->registerJs($script, $widget->position, $widget->key);
}
}