-
Notifications
You must be signed in to change notification settings - Fork 0
/
JSWidget.php
85 lines (75 loc) · 1.99 KB
/
JSWidget.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
/**
* @link https://github.com/xBazilio
* @license http://bazilio.mit-license.org/
*/
namespace xBazilio\JSWidget;
use Yii;
use yii\base\Widget;
use yii\web\View;
/**
* Outputs javascript code using yii\web\View::registerJs(). It is supposed to use in your views
* to wrap javascript code and output it in $position of rendered page. So you can use
* javascript code in views and do not worry about dependencies which have to be loaded before
* the code.
*
* For example:
*
* <?php JSWidget::begin(); ?>
* <script type="text/javascript">
* console.log('test');
* </script>
* <?php JSWidget::end(); ?>
*
* If there are two widgets with the same id, the later will take precedence and overwrite
* the former.
* For example:
*
* <?php JSWidget::begin(['id' => 'test']); ?>
* <script type="text/javascript">
* console.log('test');
* </script>
* <?php JSWidget::end(); ?>
*
* <?php JSWidget::begin(['id' => 'test']); ?>
* <script type="text/javascript">
* console.log('test overwritten');
* </script>
* <?php JSWidget::end(); ?>
*
* Only 'test overwritten' will be logged.
*
* @see yii\web\View::registerJs()
* @author Vasiliy Rumyantsev <x.bazilio@gmail.com>
*/
class JSWidget extends Widget
{
/**
* @var string
* ID that uniquely identifies this piece of JavaScript code.
*/
public $id;
/**
* @var integer
* The position of the JavaScript code.
*/
public $position = View::POS_END;
public static function begin($config = [])
{
ob_start();
return parent::begin($config);
}
public function run()
{
$output = ob_get_clean();
if (Yii::$app->request->getIsAjax()) {
echo $output;
}
else {
$output = preg_replace('/<script[^>]*>/i', '', $output);
$output = str_ireplace('</script>', '', $output);
$id = is_null($this->id) ? uniqid() : $this->id;
Yii::$app->view->registerJs($output, $this->position, $id);
}
}
}