View.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. <?php
  2. /**
  3. * @link https://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license https://www.yiiframework.com/license/
  6. */
  7. namespace yii\web;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\helpers\ArrayHelper;
  11. use yii\helpers\Html;
  12. use yii\helpers\Url;
  13. /**
  14. * View represents a view object in the MVC pattern.
  15. *
  16. * View provides a set of methods (e.g. [[render()]]) for rendering purpose.
  17. *
  18. * View is configured as an application component in [[\yii\base\Application]] by default.
  19. * You can access that instance via `Yii::$app->view`.
  20. *
  21. * You can modify its configuration by adding an array to your application config under `components`
  22. * as it is shown in the following example:
  23. *
  24. * ```php
  25. * 'view' => [
  26. * 'theme' => 'app\themes\MyTheme',
  27. * 'renderers' => [
  28. * // you may add Smarty or Twig renderer here
  29. * ]
  30. * // ...
  31. * ]
  32. * ```
  33. *
  34. * For more details and usage information on View, see the [guide article on views](guide:structure-views).
  35. *
  36. * @property \yii\web\AssetManager $assetManager The asset manager. Defaults to the "assetManager" application
  37. * component.
  38. *
  39. * @author Qiang Xue <qiang.xue@gmail.com>
  40. * @since 2.0
  41. */
  42. class View extends \yii\base\View
  43. {
  44. /**
  45. * @event Event an event that is triggered by [[beginBody()]].
  46. */
  47. const EVENT_BEGIN_BODY = 'beginBody';
  48. /**
  49. * @event Event an event that is triggered by [[endBody()]].
  50. */
  51. const EVENT_END_BODY = 'endBody';
  52. /**
  53. * The location of registered JavaScript code block or files.
  54. * This means the location is in the head section.
  55. */
  56. const POS_HEAD = 1;
  57. /**
  58. * The location of registered JavaScript code block or files.
  59. * This means the location is at the beginning of the body section.
  60. */
  61. const POS_BEGIN = 2;
  62. /**
  63. * The location of registered JavaScript code block or files.
  64. * This means the location is at the end of the body section.
  65. */
  66. const POS_END = 3;
  67. /**
  68. * The location of registered JavaScript code block.
  69. * This means the JavaScript code block will be enclosed within `jQuery(document).ready()`.
  70. */
  71. const POS_READY = 4;
  72. /**
  73. * The location of registered JavaScript code block.
  74. * This means the JavaScript code block will be enclosed within `jQuery(window).load()`.
  75. */
  76. const POS_LOAD = 5;
  77. /**
  78. * This is internally used as the placeholder for receiving the content registered for the head section.
  79. */
  80. const PH_HEAD = '<![CDATA[YII-BLOCK-HEAD]]>';
  81. /**
  82. * This is internally used as the placeholder for receiving the content registered for the beginning of the body section.
  83. */
  84. const PH_BODY_BEGIN = '<![CDATA[YII-BLOCK-BODY-BEGIN]]>';
  85. /**
  86. * This is internally used as the placeholder for receiving the content registered for the end of the body section.
  87. */
  88. const PH_BODY_END = '<![CDATA[YII-BLOCK-BODY-END]]>';
  89. /**
  90. * @var AssetBundle[] list of the registered asset bundles. The keys are the bundle names, and the values
  91. * are the registered [[AssetBundle]] objects.
  92. * @see registerAssetBundle()
  93. */
  94. public $assetBundles = [];
  95. /**
  96. * @var string the page title
  97. */
  98. public $title;
  99. /**
  100. * @var array the registered meta tags.
  101. * @see registerMetaTag()
  102. */
  103. public $metaTags = [];
  104. /**
  105. * @var array the registered link tags.
  106. * @see registerLinkTag()
  107. */
  108. public $linkTags = [];
  109. /**
  110. * @var array the registered CSS code blocks.
  111. * @see registerCss()
  112. */
  113. public $css = [];
  114. /**
  115. * @var array the registered CSS files.
  116. * @see registerCssFile()
  117. */
  118. public $cssFiles = [];
  119. /**
  120. * @var array the registered JS code blocks
  121. * @see registerJs()
  122. */
  123. public $js = [];
  124. /**
  125. * @var array the registered JS files.
  126. * @see registerJsFile()
  127. */
  128. public $jsFiles = [];
  129. /**
  130. * @since 2.0.50
  131. * @var array the script tag options.
  132. */
  133. public $scriptOptions = [];
  134. private $_assetManager;
  135. /**
  136. * Whether [[endPage()]] has been called and all files have been registered
  137. * @var bool
  138. * @since 2.0.44
  139. */
  140. protected $isPageEnded = false;
  141. /**
  142. * Marks the position of an HTML head section.
  143. */
  144. public function head()
  145. {
  146. echo self::PH_HEAD;
  147. }
  148. /**
  149. * Marks the beginning of an HTML body section.
  150. */
  151. public function beginBody()
  152. {
  153. echo self::PH_BODY_BEGIN;
  154. $this->trigger(self::EVENT_BEGIN_BODY);
  155. }
  156. /**
  157. * Marks the ending of an HTML body section.
  158. */
  159. public function endBody()
  160. {
  161. $this->trigger(self::EVENT_END_BODY);
  162. echo self::PH_BODY_END;
  163. foreach (array_keys($this->assetBundles) as $bundle) {
  164. $this->registerAssetFiles($bundle);
  165. }
  166. }
  167. /**
  168. * Marks the ending of an HTML page.
  169. * @param bool $ajaxMode whether the view is rendering in AJAX mode.
  170. * If true, the JS scripts registered at [[POS_READY]] and [[POS_LOAD]] positions
  171. * will be rendered at the end of the view like normal scripts.
  172. */
  173. public function endPage($ajaxMode = false)
  174. {
  175. $this->trigger(self::EVENT_END_PAGE);
  176. $this->isPageEnded = true;
  177. $content = ob_get_clean();
  178. echo strtr($content, [
  179. self::PH_HEAD => $this->renderHeadHtml(),
  180. self::PH_BODY_BEGIN => $this->renderBodyBeginHtml(),
  181. self::PH_BODY_END => $this->renderBodyEndHtml($ajaxMode),
  182. ]);
  183. $this->clear();
  184. }
  185. /**
  186. * Renders a view in response to an AJAX request.
  187. *
  188. * This method is similar to [[render()]] except that it will surround the view being rendered
  189. * with the calls of [[beginPage()]], [[head()]], [[beginBody()]], [[endBody()]] and [[endPage()]].
  190. * By doing so, the method is able to inject into the rendering result with JS/CSS scripts and files
  191. * that are registered with the view.
  192. *
  193. * @param string $view the view name. Please refer to [[render()]] on how to specify this parameter.
  194. * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
  195. * @param object|null $context the context that the view should use for rendering the view. If null,
  196. * existing [[context]] will be used.
  197. * @return string the rendering result
  198. * @see render()
  199. */
  200. public function renderAjax($view, $params = [], $context = null)
  201. {
  202. $viewFile = $this->findViewFile($view, $context);
  203. ob_start();
  204. ob_implicit_flush(false);
  205. $this->beginPage();
  206. $this->head();
  207. $this->beginBody();
  208. echo $this->renderFile($viewFile, $params, $context);
  209. $this->endBody();
  210. $this->endPage(true);
  211. return ob_get_clean();
  212. }
  213. /**
  214. * Registers the asset manager being used by this view object.
  215. * @return \yii\web\AssetManager the asset manager. Defaults to the "assetManager" application component.
  216. */
  217. public function getAssetManager()
  218. {
  219. return $this->_assetManager ?: Yii::$app->getAssetManager();
  220. }
  221. /**
  222. * Sets the asset manager.
  223. * @param \yii\web\AssetManager $value the asset manager
  224. */
  225. public function setAssetManager($value)
  226. {
  227. $this->_assetManager = $value;
  228. }
  229. /**
  230. * Clears up the registered meta tags, link tags, css/js scripts and files.
  231. */
  232. public function clear()
  233. {
  234. $this->metaTags = [];
  235. $this->linkTags = [];
  236. $this->css = [];
  237. $this->cssFiles = [];
  238. $this->js = [];
  239. $this->jsFiles = [];
  240. $this->assetBundles = [];
  241. }
  242. /**
  243. * Registers all files provided by an asset bundle including depending bundles files.
  244. * Removes a bundle from [[assetBundles]] once files are registered.
  245. * @param string $name name of the bundle to register
  246. */
  247. protected function registerAssetFiles($name)
  248. {
  249. if (!isset($this->assetBundles[$name])) {
  250. return;
  251. }
  252. $bundle = $this->assetBundles[$name];
  253. if ($bundle) {
  254. foreach ($bundle->depends as $dep) {
  255. $this->registerAssetFiles($dep);
  256. }
  257. $bundle->registerAssetFiles($this);
  258. }
  259. unset($this->assetBundles[$name]);
  260. }
  261. /**
  262. * Registers the named asset bundle.
  263. * All dependent asset bundles will be registered.
  264. * @param string $name the class name of the asset bundle (without the leading backslash)
  265. * @param int|null $position if set, this forces a minimum position for javascript files.
  266. * This will adjust depending assets javascript file position or fail if requirement can not be met.
  267. * If this is null, asset bundles position settings will not be changed.
  268. * See [[registerJsFile]] for more details on javascript position.
  269. * @return AssetBundle the registered asset bundle instance
  270. * @throws InvalidConfigException if the asset bundle does not exist or a circular dependency is detected
  271. */
  272. public function registerAssetBundle($name, $position = null)
  273. {
  274. if (!isset($this->assetBundles[$name])) {
  275. $am = $this->getAssetManager();
  276. $bundle = $am->getBundle($name);
  277. $this->assetBundles[$name] = false;
  278. // register dependencies
  279. $pos = isset($bundle->jsOptions['position']) ? $bundle->jsOptions['position'] : null;
  280. foreach ($bundle->depends as $dep) {
  281. $this->registerAssetBundle($dep, $pos);
  282. }
  283. $this->assetBundles[$name] = $bundle;
  284. } elseif ($this->assetBundles[$name] === false) {
  285. throw new InvalidConfigException("A circular dependency is detected for bundle '$name'.");
  286. } else {
  287. $bundle = $this->assetBundles[$name];
  288. }
  289. if ($position !== null) {
  290. $pos = isset($bundle->jsOptions['position']) ? $bundle->jsOptions['position'] : null;
  291. if ($pos === null) {
  292. $bundle->jsOptions['position'] = $pos = $position;
  293. } elseif ($pos > $position) {
  294. throw new InvalidConfigException("An asset bundle that depends on '$name' has a higher javascript file position configured than '$name'.");
  295. }
  296. // update position for all dependencies
  297. foreach ($bundle->depends as $dep) {
  298. $this->registerAssetBundle($dep, $pos);
  299. }
  300. }
  301. return $bundle;
  302. }
  303. /**
  304. * Registers a meta tag.
  305. *
  306. * For example, a description meta tag can be added like the following:
  307. *
  308. * ```php
  309. * $view->registerMetaTag([
  310. * 'name' => 'description',
  311. * 'content' => 'This website is about funny raccoons.'
  312. * ]);
  313. * ```
  314. *
  315. * will result in the meta tag `<meta name="description" content="This website is about funny raccoons.">`.
  316. *
  317. * @param array $options the HTML attributes for the meta tag.
  318. * @param string|null $key the key that identifies the meta tag. If two meta tags are registered
  319. * with the same key, the latter will overwrite the former. If this is null, the new meta tag
  320. * will be appended to the existing ones.
  321. */
  322. public function registerMetaTag($options, $key = null)
  323. {
  324. if ($key === null) {
  325. $this->metaTags[] = Html::tag('meta', '', $options);
  326. } else {
  327. $this->metaTags[$key] = Html::tag('meta', '', $options);
  328. }
  329. }
  330. /**
  331. * Registers CSRF meta tags.
  332. * They are rendered dynamically to retrieve a new CSRF token for each request.
  333. *
  334. * ```php
  335. * $view->registerCsrfMetaTags();
  336. * ```
  337. *
  338. * The above code will result in `<meta name="csrf-param" content="[yii\web\Request::$csrfParam]">`
  339. * and `<meta name="csrf-token" content="tTNpWKpdy-bx8ZmIq9R72...K1y8IP3XGkzZA==">` added to the page.
  340. *
  341. * Note: Hidden CSRF input of ActiveForm will be automatically refreshed by calling `window.yii.refreshCsrfToken()`
  342. * from `yii.js`.
  343. *
  344. * @since 2.0.13
  345. */
  346. public function registerCsrfMetaTags()
  347. {
  348. $this->metaTags['csrf_meta_tags'] = $this->renderDynamic('return yii\helpers\Html::csrfMetaTags();');
  349. }
  350. /**
  351. * Registers a link tag.
  352. *
  353. * For example, a link tag for a custom [favicon](https://www.w3.org/2005/10/howto-favicon)
  354. * can be added like the following:
  355. *
  356. * ```php
  357. * $view->registerLinkTag(['rel' => 'icon', 'type' => 'image/png', 'href' => '/myicon.png']);
  358. * ```
  359. *
  360. * which will result in the following HTML: `<link rel="icon" type="image/png" href="/myicon.png">`.
  361. *
  362. * **Note:** To register link tags for CSS stylesheets, use [[registerCssFile()]] instead, which
  363. * has more options for this kind of link tag.
  364. *
  365. * @param array $options the HTML attributes for the link tag.
  366. * @param string|null $key the key that identifies the link tag. If two link tags are registered
  367. * with the same key, the latter will overwrite the former. If this is null, the new link tag
  368. * will be appended to the existing ones.
  369. */
  370. public function registerLinkTag($options, $key = null)
  371. {
  372. if ($key === null) {
  373. $this->linkTags[] = Html::tag('link', '', $options);
  374. } else {
  375. $this->linkTags[$key] = Html::tag('link', '', $options);
  376. }
  377. }
  378. /**
  379. * Registers a CSS code block.
  380. * @param string $css the content of the CSS code block to be registered
  381. * @param array $options the HTML attributes for the `<style>`-tag.
  382. * @param string|null $key the key that identifies the CSS code block. If null, it will use
  383. * $css as the key. If two CSS code blocks are registered with the same key, the latter
  384. * will overwrite the former.
  385. */
  386. public function registerCss($css, $options = [], $key = null)
  387. {
  388. $key = $key ?: md5($css);
  389. $this->css[$key] = Html::style($css, $options);
  390. }
  391. /**
  392. * Registers a CSS file.
  393. *
  394. * This method should be used for simple registration of CSS files. If you want to use features of
  395. * [[AssetManager]] like appending timestamps to the URL and file publishing options, use [[AssetBundle]]
  396. * and [[registerAssetBundle()]] instead.
  397. *
  398. * @param string $url the CSS file to be registered.
  399. * @param array $options the HTML attributes for the link tag. Please refer to [[Html::cssFile()]] for
  400. * the supported options. The following options are specially handled and are not treated as HTML attributes:
  401. *
  402. * - `depends`: array, specifies the names of the asset bundles that this CSS file depends on.
  403. * - `appendTimestamp`: bool whether to append a timestamp to the URL.
  404. *
  405. * @param string|null $key the key that identifies the CSS script file. If null, it will use
  406. * $url as the key. If two CSS files are registered with the same key, the latter
  407. * will overwrite the former.
  408. * @throws InvalidConfigException
  409. */
  410. public function registerCssFile($url, $options = [], $key = null)
  411. {
  412. $this->registerFile('css', $url, $options, $key);
  413. }
  414. /**
  415. * Registers a JS code block.
  416. * @param string $js the JS code block to be registered
  417. * @param int $position the position at which the JS script tag should be inserted
  418. * in a page. The possible values are:
  419. *
  420. * - [[POS_HEAD]]: in the head section
  421. * - [[POS_BEGIN]]: at the beginning of the body section
  422. * - [[POS_END]]: at the end of the body section
  423. * - [[POS_LOAD]]: enclosed within jQuery(window).load().
  424. * Note that by using this position, the method will automatically register the jQuery js file.
  425. * - [[POS_READY]]: enclosed within jQuery(document).ready(). This is the default value.
  426. * Note that by using this position, the method will automatically register the jQuery js file.
  427. *
  428. * @param string|null $key the key that identifies the JS code block. If null, it will use
  429. * $js as the key. If two JS code blocks are registered with the same key, the latter
  430. * will overwrite the former.
  431. */
  432. public function registerJs($js, $position = self::POS_READY, $key = null)
  433. {
  434. $key = $key ?: md5($js);
  435. $this->js[$position][$key] = $js;
  436. if ($position === self::POS_READY || $position === self::POS_LOAD) {
  437. JqueryAsset::register($this);
  438. }
  439. }
  440. /**
  441. * Registers a JS or CSS file.
  442. *
  443. * @param string $url the JS file to be registered.
  444. * @param string $type type (js or css) of the file.
  445. * @param array $options the HTML attributes for the script tag. The following options are specially handled
  446. * and are not treated as HTML attributes:
  447. *
  448. * - `depends`: array, specifies the names of the asset bundles that this CSS file depends on.
  449. * - `appendTimestamp`: bool whether to append a timestamp to the URL.
  450. *
  451. * @param string|null $key the key that identifies the JS script file. If null, it will use
  452. * $url as the key. If two JS files are registered with the same key at the same position, the latter
  453. * will overwrite the former. Note that position option takes precedence, thus files registered with the same key,
  454. * but different position option will not override each other.
  455. * @throws InvalidConfigException
  456. */
  457. private function registerFile($type, $url, $options = [], $key = null)
  458. {
  459. $url = Yii::getAlias($url);
  460. $key = $key ?: $url;
  461. $depends = ArrayHelper::remove($options, 'depends', []);
  462. $originalOptions = $options;
  463. $position = ArrayHelper::remove($options, 'position', self::POS_END);
  464. try {
  465. $assetManagerAppendTimestamp = $this->getAssetManager()->appendTimestamp;
  466. } catch (InvalidConfigException $e) {
  467. $depends = null; // the AssetManager is not available
  468. $assetManagerAppendTimestamp = false;
  469. }
  470. $appendTimestamp = ArrayHelper::remove($options, 'appendTimestamp', $assetManagerAppendTimestamp);
  471. if ($this->isPageEnded) {
  472. Yii::warning('You\'re trying to register a file after View::endPage() has been called.');
  473. }
  474. if (empty($depends)) {
  475. // register directly without AssetManager
  476. if ($appendTimestamp && Url::isRelative($url)) {
  477. $prefix = Yii::getAlias('@web');
  478. $prefixLength = strlen($prefix);
  479. $trimmedUrl = ltrim((substr($url, 0, $prefixLength) === $prefix) ? substr($url, $prefixLength) : $url, '/');
  480. $timestamp = @filemtime(Yii::getAlias('@webroot/' . $trimmedUrl, false));
  481. if ($timestamp > 0) {
  482. $url = $timestamp ? "$url?v=$timestamp" : $url;
  483. }
  484. }
  485. if ($type === 'js') {
  486. $this->jsFiles[$position][$key] = Html::jsFile($url, $options);
  487. } else {
  488. $this->cssFiles[$key] = Html::cssFile($url, $options);
  489. }
  490. } else {
  491. $this->getAssetManager()->bundles[$key] = Yii::createObject([
  492. 'class' => AssetBundle::className(),
  493. 'baseUrl' => '',
  494. 'basePath' => '@webroot',
  495. (string)$type => [ArrayHelper::merge([!Url::isRelative($url) ? $url : ltrim($url, '/')], $originalOptions)],
  496. "{$type}Options" => $options,
  497. 'depends' => (array)$depends,
  498. ]);
  499. $this->registerAssetBundle($key);
  500. }
  501. }
  502. /**
  503. * Registers a JS file.
  504. *
  505. * This method should be used for simple registration of JS files. If you want to use features of
  506. * [[AssetManager]] like appending timestamps to the URL and file publishing options, use [[AssetBundle]]
  507. * and [[registerAssetBundle()]] instead.
  508. *
  509. * @param string $url the JS file to be registered.
  510. * @param array $options the HTML attributes for the script tag. The following options are specially handled
  511. * and are not treated as HTML attributes:
  512. *
  513. * - `depends`: array, specifies the names of the asset bundles that this JS file depends on.
  514. * - `position`: specifies where the JS script tag should be inserted in a page. The possible values are:
  515. * * [[POS_HEAD]]: in the head section
  516. * * [[POS_BEGIN]]: at the beginning of the body section
  517. * * [[POS_END]]: at the end of the body section. This is the default value.
  518. * - `appendTimestamp`: bool whether to append a timestamp to the URL.
  519. *
  520. * Please refer to [[Html::jsFile()]] for other supported options.
  521. *
  522. * @param string|null $key the key that identifies the JS script file. If null, it will use
  523. * $url as the key. If two JS files are registered with the same key at the same position, the latter
  524. * will overwrite the former. Note that position option takes precedence, thus files registered with the same key,
  525. * but different position option will not override each other.
  526. * @throws InvalidConfigException
  527. */
  528. public function registerJsFile($url, $options = [], $key = null)
  529. {
  530. $this->registerFile('js', $url, $options, $key);
  531. }
  532. /**
  533. * Registers a JS code block defining a variable. The name of variable will be
  534. * used as key, preventing duplicated variable names.
  535. *
  536. * @param string $name Name of the variable
  537. * @param array|string $value Value of the variable
  538. * @param int $position the position in a page at which the JavaScript variable should be inserted.
  539. * The possible values are:
  540. *
  541. * - [[POS_HEAD]]: in the head section. This is the default value.
  542. * - [[POS_BEGIN]]: at the beginning of the body section.
  543. * - [[POS_END]]: at the end of the body section.
  544. * - [[POS_LOAD]]: enclosed within jQuery(window).load().
  545. * Note that by using this position, the method will automatically register the jQuery js file.
  546. * - [[POS_READY]]: enclosed within jQuery(document).ready().
  547. * Note that by using this position, the method will automatically register the jQuery js file.
  548. *
  549. * @since 2.0.14
  550. */
  551. public function registerJsVar($name, $value, $position = self::POS_HEAD)
  552. {
  553. $js = sprintf('var %s = %s;', $name, \yii\helpers\Json::htmlEncode($value));
  554. $this->registerJs($js, $position, $name);
  555. }
  556. /**
  557. * Renders the content to be inserted in the head section.
  558. * The content is rendered using the registered meta tags, link tags, CSS/JS code blocks and files.
  559. * @return string the rendered content
  560. */
  561. protected function renderHeadHtml()
  562. {
  563. $lines = [];
  564. if (!empty($this->metaTags)) {
  565. $lines[] = implode("\n", $this->metaTags);
  566. }
  567. if (!empty($this->linkTags)) {
  568. $lines[] = implode("\n", $this->linkTags);
  569. }
  570. if (!empty($this->cssFiles)) {
  571. $lines[] = implode("\n", $this->cssFiles);
  572. }
  573. if (!empty($this->css)) {
  574. $lines[] = implode("\n", $this->css);
  575. }
  576. if (!empty($this->jsFiles[self::POS_HEAD])) {
  577. $lines[] = implode("\n", $this->jsFiles[self::POS_HEAD]);
  578. }
  579. if (!empty($this->js[self::POS_HEAD])) {
  580. $lines[] = Html::script(implode("\n", $this->js[self::POS_HEAD]));
  581. }
  582. return empty($lines) ? '' : implode("\n", $lines);
  583. }
  584. /**
  585. * Renders the content to be inserted at the beginning of the body section.
  586. * The content is rendered using the registered JS code blocks and files.
  587. * @return string the rendered content
  588. */
  589. protected function renderBodyBeginHtml()
  590. {
  591. $lines = [];
  592. if (!empty($this->jsFiles[self::POS_BEGIN])) {
  593. $lines[] = implode("\n", $this->jsFiles[self::POS_BEGIN]);
  594. }
  595. if (!empty($this->js[self::POS_BEGIN])) {
  596. $lines[] = Html::script(implode("\n", $this->js[self::POS_BEGIN]));
  597. }
  598. return empty($lines) ? '' : implode("\n", $lines);
  599. }
  600. /**
  601. * Renders the content to be inserted at the end of the body section.
  602. * The content is rendered using the registered JS code blocks and files.
  603. * @param bool $ajaxMode whether the view is rendering in AJAX mode.
  604. * If true, the JS scripts registered at [[POS_READY]] and [[POS_LOAD]] positions
  605. * will be rendered at the end of the view like normal scripts.
  606. * @return string the rendered content
  607. */
  608. protected function renderBodyEndHtml($ajaxMode)
  609. {
  610. $lines = [];
  611. if (!empty($this->jsFiles[self::POS_END])) {
  612. $lines[] = implode("\n", $this->jsFiles[self::POS_END]);
  613. }
  614. if ($ajaxMode) {
  615. $scripts = [];
  616. if (!empty($this->js[self::POS_END])) {
  617. $scripts[] = implode("\n", $this->js[self::POS_END]);
  618. }
  619. if (!empty($this->js[self::POS_READY])) {
  620. $scripts[] = implode("\n", $this->js[self::POS_READY]);
  621. }
  622. if (!empty($this->js[self::POS_LOAD])) {
  623. $scripts[] = implode("\n", $this->js[self::POS_LOAD]);
  624. }
  625. if (!empty($scripts)) {
  626. $lines[] = Html::script(implode("\n", $scripts));
  627. }
  628. } else {
  629. if (!empty($this->js[self::POS_END])) {
  630. $lines[] = Html::script(implode("\n", $this->js[self::POS_END]));
  631. }
  632. if (!empty($this->js[self::POS_READY])) {
  633. $js = "jQuery(function ($) {\n" . implode("\n", $this->js[self::POS_READY]) . "\n});";
  634. $lines[] = Html::script($js);
  635. }
  636. if (!empty($this->js[self::POS_LOAD])) {
  637. $js = "jQuery(window).on('load', function () {\n" . implode("\n", $this->js[self::POS_LOAD]) . "\n});";
  638. $lines[] = Html::script($js);
  639. }
  640. }
  641. return empty($lines) ? '' : implode("\n", $lines);
  642. }
  643. }