View.php 25 KB

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