View.php 25 KB

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