-
Notifications
You must be signed in to change notification settings - Fork 3
/
View.php
executable file
·87 lines (72 loc) · 2.37 KB
/
View.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
86
87
<?php
/**
* Created by PhpStorm.
* User: user1
* Date: 15.01.15
* Time: 14:44
*/
namespace anatolyrugalev\requirejs;
use yii\helpers\Html;
use yii\helpers\Url;
class View extends \yii\web\View {
private $requireJsFiles = [];
private $requireJsCode = [];
const POS_END_REQUIRED = 6;
/**
* @inheritdoc
*/
protected function renderBodyEndHtml($ajaxMode)
{
$this->getJsData();
$lines = parent::renderBodyEndHtml($ajaxMode);
$paths = $this->getRequireJsPaths();
$requireJsConfig = $this->getRequireJsConfig($paths);
$jsCode = $this->getRequireJsCode();
$lines = "<script type=\"text/javascript\">var require = {$requireJsConfig};</script>\n" . $lines;
$modulesJsArray = json_encode(array_keys($paths));
$lines .= "<script type=\"text/javascript\">require(['jquery'], function() { require({$modulesJsArray}, function() { {$jsCode} }); });</script>\n";
return $lines;
}
/**
* Gets js data for requireJs (files, code) and prevents it from Yii insert
*/
protected function getJsData()
{
$this->requireJsFiles[self::POS_END] = isset($this->jsFiles[self::POS_END]) ? $this->jsFiles[self::POS_END] : [];
$this->jsFiles[self::POS_END] = isset($this->jsFiles[self::POS_END_REQUIRED]) ? $this->jsFiles[self::POS_END_REQUIRED] : [];
if(isset($this->js[self::POS_READY])) {
$this->requireJsCode[self::POS_READY] = $this->js[self::POS_READY];
unset($this->js[self::POS_READY]);
}
if(isset($this->js[self::POS_LOAD])) {
$this->requireJsCode[self::POS_LOAD] = $this->js[self::POS_LOAD];
unset($this->js[self::POS_LOAD]);
}
}
protected function getRequireJsPaths() {
$paths = [];
$i = 0;
foreach($this->requireJsFiles as $pos => $files) {
foreach($files as $file => $htmlCode) {
$paths['yiiAsset' . $i++][] = preg_replace('#\.js$#', '', $file);
}
}
return $paths;
}
protected function getRequireJsConfig($paths)
{
return json_encode([
'paths' => $paths,
'baseUrl' => '/',
]);
}
protected function getRequireJsCode()
{
$wrapLines = [];
if (!empty($this->requireJsCode[self::POS_READY]))
$wrapLines[] = "jQuery(document).ready(function () {\n" . implode("\n", $this->requireJsCode[self::POS_READY]) . "\n});";
if (!empty($this->requireJsCode[self::POS_LOAD]))
$wrapLines[] = "jQuery(window).load(function () {\n" . implode("\n", $this->requireJsCode[self::POS_LOAD]) . "\n});";
return implode("\n", $wrapLines);
}
}