View.php 21 KB

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