You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

582 lines
21KB

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