View.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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\Html;
  10. use yii\base\InvalidConfigException;
  11. /**
  12. * View represents a view object in the MVC pattern.
  13. *
  14. * View provides a set of methods (e.g. [[render()]]) for rendering purpose.
  15. *
  16. * View is configured as an application component in [[yii\base\Application]] by default.
  17. * You can access that instance via `Yii::$app->view`.
  18. *
  19. * You can modify its configuration by adding an array to your application config under `components`
  20. * as it is shown in the following example:
  21. *
  22. * ~~~
  23. * 'view' => [
  24. * 'theme' => 'app\themes\MyTheme',
  25. * 'renderers' => [
  26. * // you may add Smarty or Twig renderer here
  27. * ]
  28. * // ...
  29. * ]
  30. * ~~~
  31. *
  32. * @property \yii\web\AssetManager $assetManager The asset manager. Defaults to the "assetManager" application
  33. * component.
  34. *
  35. * @author Qiang Xue <[email protected]>
  36. * @since 2.0
  37. */
  38. class View extends \yii\base\View
  39. {
  40. const EVENT_BEGIN_BODY = 'beginBody';
  41. /**
  42. * @event Event an event that is triggered by [[endBody()]].
  43. */
  44. const EVENT_END_BODY = 'endBody';
  45. /**
  46. * The location of registered JavaScript code block or files.
  47. * This means the location is in the head section.
  48. */
  49. const POS_HEAD = 1;
  50. /**
  51. * The location of registered JavaScript code block or files.
  52. * This means the location is at the beginning of the body section.
  53. */
  54. const POS_BEGIN = 2;
  55. /**
  56. * The location of registered JavaScript code block or files.
  57. * This means the location is at the end of the body section.
  58. */
  59. const POS_END = 3;
  60. /**
  61. * The location of registered JavaScript code block.
  62. * This means the JavaScript code block will be enclosed within `jQuery(document).ready()`.
  63. */
  64. const POS_READY = 4;
  65. /**
  66. * This is internally used as the placeholder for receiving the content registered for the head section.
  67. */
  68. const PH_HEAD = '<![CDATA[YII-BLOCK-HEAD]]>';
  69. /**
  70. * This is internally used as the placeholder for receiving the content registered for the beginning of the body section.
  71. */
  72. const PH_BODY_BEGIN = '<![CDATA[YII-BLOCK-BODY-BEGIN]]>';
  73. /**
  74. * This is internally used as the placeholder for receiving the content registered for the end of the body section.
  75. */
  76. const PH_BODY_END = '<![CDATA[YII-BLOCK-BODY-END]]>';
  77. /**
  78. * @var AssetBundle[] list of the registered asset bundles. The keys are the bundle names, and the values
  79. * are the registered [[AssetBundle]] objects.
  80. * @see registerAssetBundle()
  81. */
  82. public $assetBundles = [];
  83. /**
  84. * @var string the page title
  85. */
  86. public $title;
  87. /**
  88. * @var array the registered meta tags.
  89. * @see registerMetaTag()
  90. */
  91. public $metaTags;
  92. /**
  93. * @var array the registered link tags.
  94. * @see registerLinkTag()
  95. */
  96. public $linkTags;
  97. /**
  98. * @var array the registered CSS code blocks.
  99. * @see registerCss()
  100. */
  101. public $css;
  102. /**
  103. * @var array the registered CSS files.
  104. * @see registerCssFile()
  105. */
  106. public $cssFiles;
  107. /**
  108. * @var array the registered JS code blocks
  109. * @see registerJs()
  110. */
  111. public $js;
  112. /**
  113. * @var array the registered JS files.
  114. * @see registerJsFile()
  115. */
  116. public $jsFiles;
  117. private $_assetManager;
  118. /**
  119. * Registers the asset manager being used by this view object.
  120. * @return \yii\web\AssetManager the asset manager. Defaults to the "assetManager" application component.
  121. */
  122. public function getAssetManager()
  123. {
  124. return $this->_assetManager ?: Yii::$app->getAssetManager();
  125. }
  126. /**
  127. * Sets the asset manager.
  128. * @param \yii\web\AssetManager $value the asset manager
  129. */
  130. public function setAssetManager($value)
  131. {
  132. $this->_assetManager = $value;
  133. }
  134. /**
  135. * Marks the ending of an HTML page.
  136. */
  137. public function endPage()
  138. {
  139. $this->trigger(self::EVENT_END_PAGE);
  140. $content = ob_get_clean();
  141. foreach (array_keys($this->assetBundles) as $bundle) {
  142. $this->registerAssetFiles($bundle);
  143. }
  144. echo strtr($content, [
  145. self::PH_HEAD => $this->renderHeadHtml(),
  146. self::PH_BODY_BEGIN => $this->renderBodyBeginHtml(),
  147. self::PH_BODY_END => $this->renderBodyEndHtml(),
  148. ]);
  149. $this->metaTags = null;
  150. $this->linkTags = null;
  151. $this->css = null;
  152. $this->cssFiles = null;
  153. $this->js = null;
  154. $this->jsFiles = null;
  155. }
  156. /**
  157. * Registers all files provided by an asset bundle including depending bundles files.
  158. * Removes a bundle from [[assetBundles]] once files are registered.
  159. * @param string $name name of the bundle to register
  160. */
  161. private function registerAssetFiles($name)
  162. {
  163. if (!isset($this->assetBundles[$name])) {
  164. return;
  165. }
  166. $bundle = $this->assetBundles[$name];
  167. if ($bundle) {
  168. foreach ($bundle->depends as $dep) {
  169. $this->registerAssetFiles($dep);
  170. }
  171. $bundle->registerAssetFiles($this);
  172. }
  173. unset($this->assetBundles[$name]);
  174. }
  175. /**
  176. * Marks the beginning of an HTML body section.
  177. */
  178. public function beginBody()
  179. {
  180. echo self::PH_BODY_BEGIN;
  181. $this->trigger(self::EVENT_BEGIN_BODY);
  182. }
  183. /**
  184. * Marks the ending of an HTML body section.
  185. */
  186. public function endBody()
  187. {
  188. $this->trigger(self::EVENT_END_BODY);
  189. echo self::PH_BODY_END;
  190. }
  191. /**
  192. * Marks the position of an HTML head section.
  193. */
  194. public function head()
  195. {
  196. echo self::PH_HEAD;
  197. }
  198. /**
  199. * Registers the named asset bundle.
  200. * All dependent asset bundles will be registered.
  201. * @param string $name the name of the asset bundle.
  202. * @param integer|null $position if set, this forces a minimum position for javascript files.
  203. * This will adjust depending assets javascript file position or fail if requirement can not be met.
  204. * If this is null, asset bundles position settings will not be changed.
  205. * See [[registerJsFile]] for more details on javascript position.
  206. * @return AssetBundle the registered asset bundle instance
  207. * @throws InvalidConfigException if the asset bundle does not exist or a circular dependency is detected
  208. */
  209. public function registerAssetBundle($name, $position = null)
  210. {
  211. if (!isset($this->assetBundles[$name])) {
  212. $am = $this->getAssetManager();
  213. $bundle = $am->getBundle($name);
  214. $this->assetBundles[$name] = false;
  215. // register dependencies
  216. $pos = isset($bundle->jsOptions['position']) ? $bundle->jsOptions['position'] : null;
  217. foreach ($bundle->depends as $dep) {
  218. $this->registerAssetBundle($dep, $pos);
  219. }
  220. $this->assetBundles[$name] = $bundle;
  221. } elseif ($this->assetBundles[$name] === false) {
  222. throw new InvalidConfigException("A circular dependency is detected for bundle '$name'.");
  223. } else {
  224. $bundle = $this->assetBundles[$name];
  225. }
  226. if ($position !== null) {
  227. $pos = isset($bundle->jsOptions['position']) ? $bundle->jsOptions['position'] : null;
  228. if ($pos === null) {
  229. $bundle->jsOptions['position'] = $pos = $position;
  230. } elseif ($pos > $position) {
  231. throw new InvalidConfigException("An asset bundle that depends on '$name' has a higher javascript file position configured than '$name'.");
  232. }
  233. // update position for all dependencies
  234. foreach ($bundle->depends as $dep) {
  235. $this->registerAssetBundle($dep, $pos);
  236. }
  237. }
  238. return $bundle;
  239. }
  240. /**
  241. * Registers a meta tag.
  242. * @param array $options the HTML attributes for the meta tag.
  243. * @param string $key the key that identifies the meta tag. If two meta tags are registered
  244. * with the same key, the latter will overwrite the former. If this is null, the new meta tag
  245. * will be appended to the existing ones.
  246. */
  247. public function registerMetaTag($options, $key = null)
  248. {
  249. if ($key === null) {
  250. $this->metaTags[] = Html::tag('meta', '', $options);
  251. } else {
  252. $this->metaTags[$key] = Html::tag('meta', '', $options);
  253. }
  254. }
  255. /**
  256. * Registers a link tag.
  257. * @param array $options the HTML attributes for the link tag.
  258. * @param string $key the key that identifies the link tag. If two link tags are registered
  259. * with the same key, the latter will overwrite the former. If this is null, the new link tag
  260. * will be appended to the existing ones.
  261. */
  262. public function registerLinkTag($options, $key = null)
  263. {
  264. if ($key === null) {
  265. $this->linkTags[] = Html::tag('link', '', $options);
  266. } else {
  267. $this->linkTags[$key] = Html::tag('link', '', $options);
  268. }
  269. }
  270. /**
  271. * Registers a CSS code block.
  272. * @param string $css the CSS code block to be registered
  273. * @param array $options the HTML attributes for the style tag.
  274. * @param string $key the key that identifies the CSS code block. If null, it will use
  275. * $css as the key. If two CSS code blocks are registered with the same key, the latter
  276. * will overwrite the former.
  277. */
  278. public function registerCss($css, $options = [], $key = null)
  279. {
  280. $key = $key ?: md5($css);
  281. $this->css[$key] = Html::style($css, $options);
  282. }
  283. /**
  284. * Registers a CSS file.
  285. * @param string $url the CSS file to be registered.
  286. * @param array $depends the names of the asset bundles that this CSS file depends on
  287. * @param array $options the HTML attributes for the link tag.
  288. * @param string $key the key that identifies the CSS script file. If null, it will use
  289. * $url as the key. If two CSS files are registered with the same key, the latter
  290. * will overwrite the former.
  291. */
  292. public function registerCssFile($url, $depends = [], $options = [], $key = null)
  293. {
  294. $key = $key ?: $url;
  295. if (empty($depends)) {
  296. $this->cssFiles[$key] = Html::cssFile($url, $options);
  297. } else {
  298. $am = Yii::$app->getAssetManager();
  299. $am->bundles[$key] = new AssetBundle([
  300. 'css' => [$url],
  301. 'cssOptions' => $options,
  302. 'depends' => (array)$depends,
  303. ]);
  304. $this->registerAssetBundle($key);
  305. }
  306. }
  307. /**
  308. * Registers a JS code block.
  309. * @param string $js the JS code block to be registered
  310. * @param integer $position the position at which the JS script tag should be inserted
  311. * in a page. The possible values are:
  312. *
  313. * - [[POS_HEAD]]: in the head section
  314. * - [[POS_BEGIN]]: at the beginning of the body section
  315. * - [[POS_END]]: at the end of the body section
  316. * - [[POS_READY]]: enclosed within jQuery(document).ready(). This is the default value.
  317. * Note that by using this position, the method will automatically register the jQuery js file.
  318. *
  319. * @param string $key the key that identifies the JS code block. If null, it will use
  320. * $js as the key. If two JS code blocks are registered with the same key, the latter
  321. * will overwrite the former.
  322. */
  323. public function registerJs($js, $position = self::POS_READY, $key = null)
  324. {
  325. $key = $key ?: md5($js);
  326. $this->js[$position][$key] = $js;
  327. if ($position === self::POS_READY) {
  328. JqueryAsset::register($this);
  329. }
  330. }
  331. /**
  332. * Registers a JS file.
  333. * @param string $url the JS file to be registered.
  334. * @param array $depends the names of the asset bundles that this JS file depends on
  335. * @param array $options the HTML attributes for the script tag. A special option
  336. * named "position" is supported which specifies where the JS script tag should be inserted
  337. * in a page. The possible values of "position" are:
  338. *
  339. * - [[POS_HEAD]]: in the head section
  340. * - [[POS_BEGIN]]: at the beginning of the body section
  341. * - [[POS_END]]: at the end of the body section. This is the default value.
  342. *
  343. * @param string $key the key that identifies the JS script file. If null, it will use
  344. * $url as the key. If two JS files are registered with the same key, the latter
  345. * will overwrite the former.
  346. */
  347. public function registerJsFile($url, $depends = [], $options = [], $key = null)
  348. {
  349. $key = $key ?: $url;
  350. if (empty($depends)) {
  351. $position = isset($options['position']) ? $options['position'] : self::POS_END;
  352. unset($options['position']);
  353. $this->jsFiles[$position][$key] = Html::jsFile($url, $options);
  354. } else {
  355. $am = Yii::$app->getAssetManager();
  356. $am->bundles[$key] = new AssetBundle([
  357. 'js' => [$url],
  358. 'jsOptions' => $options,
  359. 'depends' => (array)$depends,
  360. ]);
  361. $this->registerAssetBundle($key);
  362. }
  363. }
  364. /**
  365. * Renders the content to be inserted in the head section.
  366. * The content is rendered using the registered meta tags, link tags, CSS/JS code blocks and files.
  367. * @return string the rendered content
  368. */
  369. protected function renderHeadHtml()
  370. {
  371. $lines = [];
  372. if (!empty($this->metaTags)) {
  373. $lines[] = implode("\n", $this->metaTags);
  374. }
  375. $request = Yii::$app->getRequest();
  376. if ($request instanceof \yii\web\Request && $request->enableCsrfValidation) {
  377. $lines[] = Html::tag('meta', '', ['name' => 'csrf-var', 'content' => $request->csrfVar]);
  378. $lines[] = Html::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]);
  379. }
  380. if (!empty($this->linkTags)) {
  381. $lines[] = implode("\n", $this->linkTags);
  382. }
  383. if (!empty($this->cssFiles)) {
  384. $lines[] = implode("\n", $this->cssFiles);
  385. }
  386. if (!empty($this->css)) {
  387. $lines[] = implode("\n", $this->css);
  388. }
  389. if (!empty($this->jsFiles[self::POS_HEAD])) {
  390. $lines[] = implode("\n", $this->jsFiles[self::POS_HEAD]);
  391. }
  392. if (!empty($this->js[self::POS_HEAD])) {
  393. $lines[] = Html::script(implode("\n", $this->js[self::POS_HEAD]), ['type' => 'text/javascript']);
  394. }
  395. return empty($lines) ? '' : implode("\n", $lines);
  396. }
  397. /**
  398. * Renders the content to be inserted at the beginning of the body section.
  399. * The content is rendered using the registered JS code blocks and files.
  400. * @return string the rendered content
  401. */
  402. protected function renderBodyBeginHtml()
  403. {
  404. $lines = [];
  405. if (!empty($this->jsFiles[self::POS_BEGIN])) {
  406. $lines[] = implode("\n", $this->jsFiles[self::POS_BEGIN]);
  407. }
  408. if (!empty($this->js[self::POS_BEGIN])) {
  409. $lines[] = Html::script(implode("\n", $this->js[self::POS_BEGIN]), ['type' => 'text/javascript']);
  410. }
  411. return empty($lines) ? '' : implode("\n", $lines);
  412. }
  413. /**
  414. * Renders the content to be inserted at the end of the body section.
  415. * The content is rendered using the registered JS code blocks and files.
  416. * @return string the rendered content
  417. */
  418. protected function renderBodyEndHtml()
  419. {
  420. $lines = [];
  421. if (!empty($this->jsFiles[self::POS_END])) {
  422. $lines[] = implode("\n", $this->jsFiles[self::POS_END]);
  423. }
  424. if (!empty($this->js[self::POS_END])) {
  425. $lines[] = Html::script(implode("\n", $this->js[self::POS_END]), ['type' => 'text/javascript']);
  426. }
  427. if (!empty($this->js[self::POS_READY])) {
  428. $js = "jQuery(document).ready(function(){\n" . implode("\n", $this->js[self::POS_READY]) . "\n});";
  429. $lines[] = Html::script($js, ['type' => 'text/javascript']);
  430. }
  431. return empty($lines) ? '' : implode("\n", $lines);
  432. }
  433. }