Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

552 lines
20KB

  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. * ~~~
  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. * @param array $options the HTML attributes for the meta tag.
  291. * @param string $key the key that identifies the meta tag. If two meta tags are registered
  292. * with the same key, the latter will overwrite the former. If this is null, the new meta tag
  293. * will be appended to the existing ones.
  294. */
  295. public function registerMetaTag($options, $key = null)
  296. {
  297. if ($key === null) {
  298. $this->metaTags[] = Html::tag('meta', '', $options);
  299. } else {
  300. $this->metaTags[$key] = Html::tag('meta', '', $options);
  301. }
  302. }
  303. /**
  304. * Registers a link tag.
  305. * @param array $options the HTML attributes for the link tag.
  306. * @param string $key the key that identifies the link tag. If two link tags are registered
  307. * with the same key, the latter will overwrite the former. If this is null, the new link tag
  308. * will be appended to the existing ones.
  309. */
  310. public function registerLinkTag($options, $key = null)
  311. {
  312. if ($key === null) {
  313. $this->linkTags[] = Html::tag('link', '', $options);
  314. } else {
  315. $this->linkTags[$key] = Html::tag('link', '', $options);
  316. }
  317. }
  318. /**
  319. * Registers a CSS code block.
  320. * @param string $css the CSS code block to be registered
  321. * @param array $options the HTML attributes for the style tag.
  322. * @param string $key the key that identifies the CSS code block. If null, it will use
  323. * $css as the key. If two CSS code blocks are registered with the same key, the latter
  324. * will overwrite the former.
  325. */
  326. public function registerCss($css, $options = [], $key = null)
  327. {
  328. $key = $key ?: md5($css);
  329. $this->css[$key] = Html::style($css, $options);
  330. }
  331. /**
  332. * Registers a CSS file.
  333. * @param string $url the CSS file to be registered.
  334. * @param array $options the HTML attributes for the link tag. Please refer to [[Html::cssFile()]] for
  335. * the supported options. The following options are specially handled and are not treated as HTML attributes:
  336. *
  337. * - `depends`: array, specifies the names of the asset bundles that this CSS file depends on.
  338. *
  339. * @param string $key the key that identifies the CSS script file. If null, it will use
  340. * $url as the key. If two CSS files are registered with the same key, the latter
  341. * will overwrite the former.
  342. */
  343. public function registerCssFile($url, $options = [], $key = null)
  344. {
  345. $url = Yii::getAlias($url);
  346. $key = $key ?: $url;
  347. $depends = ArrayHelper::remove($options, 'depends', []);
  348. if (empty($depends)) {
  349. $this->cssFiles[$key] = Html::cssFile($url, $options);
  350. } else {
  351. $this->getAssetManager()->bundles[$key] = new AssetBundle([
  352. 'baseUrl' => '',
  353. 'css' => [strncmp($url, '//', 2) === 0 ? $url : ltrim($url, '/')],
  354. 'cssOptions' => $options,
  355. 'depends' => (array) $depends,
  356. ]);
  357. $this->registerAssetBundle($key);
  358. }
  359. }
  360. /**
  361. * Registers a JS code block.
  362. * @param string $js the JS code block to be registered
  363. * @param integer $position the position at which the JS script tag should be inserted
  364. * in a page. The possible values are:
  365. *
  366. * - [[POS_HEAD]]: in the head section
  367. * - [[POS_BEGIN]]: at the beginning of the body section
  368. * - [[POS_END]]: at the end of the body section
  369. * - [[POS_LOAD]]: enclosed within jQuery(window).load().
  370. * Note that by using this position, the method will automatically register the jQuery js file.
  371. * - [[POS_READY]]: enclosed within jQuery(document).ready(). This is the default value.
  372. * Note that by using this position, the method will automatically register the jQuery js file.
  373. *
  374. * @param string $key the key that identifies the JS code block. If null, it will use
  375. * $js as the key. If two JS code blocks are registered with the same key, the latter
  376. * will overwrite the former.
  377. */
  378. public function registerJs($js, $position = self::POS_READY, $key = null)
  379. {
  380. $key = $key ?: md5($js);
  381. $this->js[$position][$key] = $js;
  382. if ($position === self::POS_READY || $position === self::POS_LOAD) {
  383. JqueryAsset::register($this);
  384. }
  385. }
  386. /**
  387. * Registers a JS file.
  388. * @param string $url the JS file to be registered.
  389. * @param array $options the HTML attributes for the script tag. The following options are specially handled
  390. * and are not treated as HTML attributes:
  391. *
  392. * - `depends`: array, specifies the names of the asset bundles that this JS file depends on.
  393. * - `position`: specifies where the JS script tag should be inserted in a page. The possible values are:
  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. This is the default value.
  397. *
  398. * Please refer to [[Html::jsFile()]] for other supported options.
  399. *
  400. * @param string $key the key that identifies the JS script file. If null, it will use
  401. * $url as the key. If two JS files are registered with the same key, the latter
  402. * will overwrite the former.
  403. */
  404. public function registerJsFile($url, $options = [], $key = null)
  405. {
  406. $url = Yii::getAlias($url);
  407. $key = $key ?: $url;
  408. $depends = ArrayHelper::remove($options, 'depends', []);
  409. if (empty($depends)) {
  410. $position = ArrayHelper::remove($options, 'position', self::POS_END);
  411. $this->jsFiles[$position][$key] = Html::jsFile($url, $options);
  412. } else {
  413. $this->getAssetManager()->bundles[$key] = new AssetBundle([
  414. 'baseUrl' => '',
  415. 'js' => [strncmp($url, '//', 2) === 0 ? $url : ltrim($url, '/')],
  416. 'jsOptions' => $options,
  417. 'depends' => (array) $depends,
  418. ]);
  419. $this->registerAssetBundle($key);
  420. }
  421. }
  422. /**
  423. * Renders the content to be inserted in the head section.
  424. * The content is rendered using the registered meta tags, link tags, CSS/JS code blocks and files.
  425. * @return string the rendered content
  426. */
  427. protected function renderHeadHtml()
  428. {
  429. $lines = [];
  430. if (!empty($this->metaTags)) {
  431. $lines[] = implode("\n", $this->metaTags);
  432. }
  433. if (!empty($this->linkTags)) {
  434. $lines[] = implode("\n", $this->linkTags);
  435. }
  436. if (!empty($this->cssFiles)) {
  437. $lines[] = implode("\n", $this->cssFiles);
  438. }
  439. if (!empty($this->css)) {
  440. $lines[] = implode("\n", $this->css);
  441. }
  442. if (!empty($this->jsFiles[self::POS_HEAD])) {
  443. $lines[] = implode("\n", $this->jsFiles[self::POS_HEAD]);
  444. }
  445. if (!empty($this->js[self::POS_HEAD])) {
  446. $lines[] = Html::script(implode("\n", $this->js[self::POS_HEAD]), ['type' => 'text/javascript']);
  447. }
  448. return empty($lines) ? '' : implode("\n", $lines);
  449. }
  450. /**
  451. * Renders the content to be inserted at the beginning of the body section.
  452. * The content is rendered using the registered JS code blocks and files.
  453. * @return string the rendered content
  454. */
  455. protected function renderBodyBeginHtml()
  456. {
  457. $lines = [];
  458. if (!empty($this->jsFiles[self::POS_BEGIN])) {
  459. $lines[] = implode("\n", $this->jsFiles[self::POS_BEGIN]);
  460. }
  461. if (!empty($this->js[self::POS_BEGIN])) {
  462. $lines[] = Html::script(implode("\n", $this->js[self::POS_BEGIN]), ['type' => 'text/javascript']);
  463. }
  464. return empty($lines) ? '' : implode("\n", $lines);
  465. }
  466. /**
  467. * Renders the content to be inserted at the end of the body section.
  468. * The content is rendered using the registered JS code blocks and files.
  469. * @param boolean $ajaxMode whether the view is rendering in AJAX mode.
  470. * If true, the JS scripts registered at [[POS_READY]] and [[POS_LOAD]] positions
  471. * will be rendered at the end of the view like normal scripts.
  472. * @return string the rendered content
  473. */
  474. protected function renderBodyEndHtml($ajaxMode)
  475. {
  476. $lines = [];
  477. if (!empty($this->jsFiles[self::POS_END])) {
  478. $lines[] = implode("\n", $this->jsFiles[self::POS_END]);
  479. }
  480. if ($ajaxMode) {
  481. $scripts = [];
  482. if (!empty($this->js[self::POS_END])) {
  483. $scripts[] = implode("\n", $this->js[self::POS_END]);
  484. }
  485. if (!empty($this->js[self::POS_READY])) {
  486. $scripts[] = implode("\n", $this->js[self::POS_READY]);
  487. }
  488. if (!empty($this->js[self::POS_LOAD])) {
  489. $scripts[] = implode("\n", $this->js[self::POS_LOAD]);
  490. }
  491. if (!empty($scripts)) {
  492. $lines[] = Html::script(implode("\n", $scripts), ['type' => 'text/javascript']);
  493. }
  494. } else {
  495. if (!empty($this->js[self::POS_END])) {
  496. $lines[] = Html::script(implode("\n", $this->js[self::POS_END]), ['type' => 'text/javascript']);
  497. }
  498. if (!empty($this->js[self::POS_READY])) {
  499. $js = "jQuery(document).ready(function () {\n" . implode("\n", $this->js[self::POS_READY]) . "\n});";
  500. $lines[] = Html::script($js, ['type' => 'text/javascript']);
  501. }
  502. if (!empty($this->js[self::POS_LOAD])) {
  503. $js = "jQuery(window).load(function () {\n" . implode("\n", $this->js[self::POS_LOAD]) . "\n});";
  504. $lines[] = Html::script($js, ['type' => 'text/javascript']);
  505. }
  506. }
  507. return empty($lines) ? '' : implode("\n", $lines);
  508. }
  509. }