View.php 27.4 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7 8 9
 * @license http://www.yiiframework.com/license/
 */

namespace yii\base;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\helpers\FileHelper;
12
use yii\helpers\Html;
13 14
use yii\web\JqueryAsset;
use yii\web\AssetBundle;
15 16 17
use yii\widgets\Block;
use yii\widgets\ContentDecorator;
use yii\widgets\FragmentCache;
Qiang Xue committed
18

Qiang Xue committed
19
/**
Qiang Xue committed
20
 * View represents a view object in the MVC pattern.
Qiang Xue committed
21
 *
Qiang Xue committed
22
 * View provides a set of methods (e.g. [[render()]]) for rendering purpose.
Qiang Xue committed
23
 *
24 25
 * @property \yii\web\AssetManager $assetManager The asset manager. Defaults to the "assetManager" application
 * component.
26
 *
Qiang Xue committed
27 28 29 30 31
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class View extends Component
{
32
	/**
Qiang Xue committed
33
	 * @event Event an event that is triggered by [[beginPage()]].
34 35 36
	 */
	const EVENT_BEGIN_PAGE = 'beginPage';
	/**
Qiang Xue committed
37
	 * @event Event an event that is triggered by [[endPage()]].
38 39
	 */
	const EVENT_END_PAGE = 'endPage';
Qiang Xue committed
40 41 42 43 44 45 46 47
	/**
	 * @event Event an event that is triggered by [[beginBody()]].
	 */
	const EVENT_BEGIN_BODY = 'beginBody';
	/**
	 * @event Event an event that is triggered by [[endBody()]].
	 */
	const EVENT_END_BODY = 'endBody';
48
	/**
49
	 * @event ViewEvent an event that is triggered by [[renderFile()]] right before it renders a view file.
50 51 52
	 */
	const EVENT_BEFORE_RENDER = 'beforeRender';
	/**
53
	 * @event ViewEvent an event that is triggered by [[renderFile()]] right after it renders a view file.
54 55 56
	 */
	const EVENT_AFTER_RENDER = 'afterRender';

Qiang Xue committed
57
	/**
58 59
	 * The location of registered JavaScript code block or files.
	 * This means the location is in the head section.
Qiang Xue committed
60
	 */
61 62 63 64 65 66 67 68 69 70 71
	const POS_HEAD = 1;
	/**
	 * The location of registered JavaScript code block or files.
	 * This means the location is at the beginning of the body section.
	 */
	const POS_BEGIN = 2;
	/**
	 * The location of registered JavaScript code block or files.
	 * This means the location is at the end of the body section.
	 */
	const POS_END = 3;
72 73 74 75 76
	/**
	 * The location of registered JavaScript code block.
	 * This means the JavaScript code block will be enclosed within `jQuery(document).ready()`.
	 */
	const POS_READY = 4;
77 78 79
	/**
	 * This is internally used as the placeholder for receiving the content registered for the head section.
	 */
80
	const PH_HEAD = '<![CDATA[YII-BLOCK-HEAD]]>';
81 82 83
	/**
	 * This is internally used as the placeholder for receiving the content registered for the beginning of the body section.
	 */
84
	const PH_BODY_BEGIN = '<![CDATA[YII-BLOCK-BODY-BEGIN]]>';
Qiang Xue committed
85
	/**
86
	 * This is internally used as the placeholder for receiving the content registered for the end of the body section.
Qiang Xue committed
87
	 */
88
	const PH_BODY_END = '<![CDATA[YII-BLOCK-BODY-END]]>';
89 90 91


	/**
92
	 * @var ViewContextInterface the context under which the [[renderFile()]] method is being invoked.
93 94
	 */
	public $context;
Qiang Xue committed
95
	/**
Qiang Xue committed
96
	 * @var mixed custom parameters that are shared among view templates.
Qiang Xue committed
97
	 */
Alexander Makarov committed
98
	public $params = [];
Qiang Xue committed
99
	/**
Qiang Xue committed
100 101
	 * @var array a list of available renderers indexed by their corresponding supported file extensions.
	 * Each renderer may be a view renderer object or the configuration for creating the renderer object.
102 103 104
	 * For example, the following configuration enables both Smarty and Twig view renderers:
	 *
	 * ~~~
Alexander Makarov committed
105 106 107 108
	 * [
	 *     'tpl' => ['class' => 'yii\smarty\ViewRenderer'],
	 *     'twig' => ['class' => 'yii\twig\ViewRenderer'],
	 * ]
109
	 * ~~~
Qiang Xue committed
110 111 112
	 *
	 * If no renderer is available for the given view file, the view file will be treated as a normal PHP
	 * and rendered via [[renderPhpFile()]].
Qiang Xue committed
113
	 */
114
	public $renderers;
115
	/**
116
	 * @var Theme|array the theme object or the configuration array for creating the theme object.
Qiang Xue committed
117
	 * If not set, it means theming is not enabled.
118
	 */
Qiang Xue committed
119
	public $theme;
Qiang Xue committed
120
	/**
Qiang Xue committed
121 122
	 * @var array a list of named output blocks. The keys are the block names and the values
	 * are the corresponding block content. You can call [[beginBlock()]] and [[endBlock()]]
123
	 * to capture small fragments of a view. They can be later accessed somewhere else
Qiang Xue committed
124 125
	 * through this property.
	 */
Qiang Xue committed
126
	public $blocks;
Qiang Xue committed
127 128
	/**
	 * @var array a list of currently active fragment cache widgets. This property
129 130
	 * is used internally to implement the content caching feature. Do not modify it directly.
	 * @internal
Qiang Xue committed
131
	 */
Alexander Makarov committed
132
	public $cacheStack = [];
Qiang Xue committed
133 134
	/**
	 * @var array a list of placeholders for embedding dynamic contents. This property
135 136
	 * is used internally to implement the content caching feature. Do not modify it directly.
	 * @internal
Qiang Xue committed
137
	 */
Alexander Makarov committed
138
	public $dynamicPlaceholders = [];
139
	/**
Carsten Brandt committed
140 141
	 * @var AssetBundle[] list of the registered asset bundles. The keys are the bundle names, and the values
	 * are the registered [[AssetBundle]] objects.
142 143
	 * @see registerAssetBundle
	 */
Alexander Makarov committed
144
	public $assetBundles = [];
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
	/**
	 * @var string the page title
	 */
	public $title;
	/**
	 * @var array the registered meta tags.
	 * @see registerMetaTag
	 */
	public $metaTags;
	/**
	 * @var array the registered link tags.
	 * @see registerLinkTag
	 */
	public $linkTags;
	/**
	 * @var array the registered CSS code blocks.
	 * @see registerCss
	 */
	public $css;
	/**
	 * @var array the registered CSS files.
	 * @see registerCssFile
	 */
	public $cssFiles;
	/**
	 * @var array the registered JS code blocks
	 * @see registerJs
	 */
	public $js;
	/**
	 * @var array the registered JS files.
	 * @see registerJsFile
	 */
	public $jsFiles;
Qiang Xue committed
179 180


Qiang Xue committed
181
	/**
Qiang Xue committed
182
	 * Initializes the view component.
Qiang Xue committed
183
	 */
Qiang Xue committed
184
	public function init()
Qiang Xue committed
185
	{
Qiang Xue committed
186 187
		parent::init();
		if (is_array($this->theme)) {
188 189 190
			if (!isset($this->theme['class'])) {
				$this->theme['class'] = 'yii\base\Theme';
			}
Qiang Xue committed
191
			$this->theme = Yii::createObject($this->theme);
Qiang Xue committed
192 193 194
		}
	}

Qiang Xue committed
195
	/**
Qiang Xue committed
196
	 * Renders a view.
Qiang Xue committed
197
	 *
198
	 * The view to be rendered can be specified in one of the following formats:
Qiang Xue committed
199
	 *
200 201 202 203 204 205
	 * - path alias (e.g. "@app/views/site/index");
	 * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
	 *   The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
	 * - absolute path within current module (e.g. "/site/index"): the view name starts with a single slash.
	 *   The actual view file will be looked for under the [[Module::viewPath|view path]] of [[module]].
	 * - resolving any other format will be performed via [[ViewContext::findViewFile()]].
Qiang Xue committed
206 207 208
	 *
	 * @param string $view the view name. Please refer to [[Controller::findViewFile()]]
	 * and [[Widget::findViewFile()]] on how to specify this parameter.
Qiang Xue committed
209
	 * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
210 211
	 * @param object $context the context that the view should use for rendering the view. If null,
	 * existing [[context]] will be used.
212
	 * @return string the rendering result
Qiang Xue committed
213 214
	 * @throws InvalidParamException if the view cannot be resolved or the view file does not exist.
	 * @see renderFile
Qiang Xue committed
215
	 */
216
	public function render($view, $params = [], $context = null)
Qiang Xue committed
217
	{
218 219 220 221 222 223 224 225 226 227 228
		$viewFile = $this->findViewFile($view, $context);
		return $this->renderFile($viewFile, $params, $context);
	}

	/**
	 * Finds the view file based on the given view name.
	 * @param string $view the view name or the path alias of the view file. Please refer to [[render()]]
	 * on how to specify this parameter.
	 * @param object $context the context that the view should be used to search the view file. If null,
	 * existing [[context]] will be used.
	 * @return string the view file path. Note that the file may not exist.
229
	 * @throws InvalidCallException if [[context]] is required and invalid.
230 231 232 233 234 235 236 237 238
	 */
	protected function findViewFile($view, $context = null)
	{
		if (strncmp($view, '@', 1) === 0) {
			// e.g. "@app/views/main"
			$file = Yii::getAlias($view);
		} elseif (strncmp($view, '//', 2) === 0) {
			// e.g. "//layouts/main"
			$file = Yii::$app->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
239
		} elseif (strncmp($view, '/', 1) === 0) {
240
			// e.g. "/site/index"
241 242 243 244 245
			if (Yii::$app->controller !== null) {
				$file = Yii::$app->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
			} else {
				throw new InvalidCallException("Unable to locate view file for view '$view': no active controller.");
			}
Qiang Xue committed
246
		} else {
247 248 249 250
			// context required
			if ($context === null) {
				$context = $this->context;
			}
251
			if ($context instanceof ViewContextInterface) {
252 253
				$file = $context->findViewFile($view);
			} else {
254
				throw new InvalidCallException("Unable to locate view file for view '$view': no active view context.");
255
			}
Qiang Xue committed
256
		}
257 258

		return pathinfo($file, PATHINFO_EXTENSION) === '' ? $file . '.php' : $file;
Qiang Xue committed
259 260
	}

Qiang Xue committed
261 262
	/**
	 * Renders a view file.
Qiang Xue committed
263
	 *
Qiang Xue committed
264 265
	 * If [[theme]] is enabled (not null), it will try to render the themed version of the view file as long
	 * as it is available.
Qiang Xue committed
266
	 *
Qiang Xue committed
267 268 269 270 271 272
	 * The method will call [[FileHelper::localize()]] to localize the view file.
	 *
	 * If [[renderer]] is enabled (not null), the method will use it to render the view file.
	 * Otherwise, it will simply include the view file as a normal PHP file, capture its output and
	 * return it as a string.
	 *
Qiang Xue committed
273
	 * @param string $viewFile the view file. This can be either a file path or a path alias.
Qiang Xue committed
274
	 * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
Qiang Xue committed
275 276
	 * @param object $context the context that the view should use for rendering the view. If null,
	 * existing [[context]] will be used.
Qiang Xue committed
277
	 * @return string the rendering result
Qiang Xue committed
278
	 * @throws InvalidParamException if the view file does not exist
Qiang Xue committed
279
	 */
Alexander Makarov committed
280
	public function renderFile($viewFile, $params = [], $context = null)
Qiang Xue committed
281
	{
Qiang Xue committed
282
		$viewFile = Yii::getAlias($viewFile);
283 284 285
		if ($this->theme !== null) {
			$viewFile = $this->theme->applyTo($viewFile);
		}
Qiang Xue committed
286 287 288 289 290 291
		if (is_file($viewFile)) {
			$viewFile = FileHelper::localize($viewFile);
		} else {
			throw new InvalidParamException("The view file does not exist: $viewFile");
		}

Qiang Xue committed
292
		$oldContext = $this->context;
Qiang Xue committed
293 294 295
		if ($context !== null) {
			$this->context = $context;
		}
Qiang Xue committed
296

297 298
		$output = '';
		if ($this->beforeRender($viewFile)) {
Qiang Xue committed
299
			Yii::trace("Rendering view file: $viewFile", __METHOD__);
Qiang Xue committed
300 301
			$ext = pathinfo($viewFile, PATHINFO_EXTENSION);
			if (isset($this->renderers[$ext])) {
Qiang Xue committed
302
				if (is_array($this->renderers[$ext]) || is_string($this->renderers[$ext])) {
Qiang Xue committed
303 304 305 306 307
					$this->renderers[$ext] = Yii::createObject($this->renderers[$ext]);
				}
				/** @var ViewRenderer $renderer */
				$renderer = $this->renderers[$ext];
				$output = $renderer->render($this, $viewFile, $params);
308 309 310 311
			} else {
				$output = $this->renderPhpFile($viewFile, $params);
			}
			$this->afterRender($viewFile, $output);
Qiang Xue committed
312
		}
Qiang Xue committed
313 314 315 316

		$this->context = $oldContext;

		return $output;
Qiang Xue committed
317 318
	}

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
	/**
	 * This method is invoked right before [[renderFile()]] renders a view file.
	 * The default implementation will trigger the [[EVENT_BEFORE_RENDER]] event.
	 * If you override this method, make sure you call the parent implementation first.
	 * @param string $viewFile the view file to be rendered
	 * @return boolean whether to continue rendering the view file.
	 */
	public function beforeRender($viewFile)
	{
		$event = new ViewEvent($viewFile);
		$this->trigger(self::EVENT_BEFORE_RENDER, $event);
		return $event->isValid;
	}

	/**
	 * This method is invoked right after [[renderFile()]] renders a view file.
	 * The default implementation will trigger the [[EVENT_AFTER_RENDER]] event.
	 * If you override this method, make sure you call the parent implementation first.
	 * @param string $viewFile the view file to be rendered
	 * @param string $output the rendering result of the view file. Updates to this parameter
	 * will be passed back and returned by [[renderFile()]].
	 */
	public function afterRender($viewFile, &$output)
	{
		if ($this->hasEventHandlers(self::EVENT_AFTER_RENDER)) {
			$event = new ViewEvent($viewFile);
			$event->output = $output;
			$this->trigger(self::EVENT_AFTER_RENDER, $event);
			$output = $event->output;
		}
	}

Qiang Xue committed
351
	/**
Qiang Xue committed
352 353 354 355 356 357
	 * Renders a view file as a PHP script.
	 *
	 * This method treats the view file as a PHP script and includes the file.
	 * It extracts the given parameters and makes them available in the view file.
	 * The method captures the output of the included view file and returns it as a string.
	 *
Qiang Xue committed
358 359
	 * This method should mainly be called by view renderer or [[renderFile()]].
	 *
Qiang Xue committed
360 361 362
	 * @param string $_file_ the view file.
	 * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file.
	 * @return string the rendering result
Qiang Xue committed
363
	 */
Alexander Makarov committed
364
	public function renderPhpFile($_file_, $_params_ = [])
Qiang Xue committed
365
	{
Qiang Xue committed
366 367 368 369 370
		ob_start();
		ob_implicit_flush(false);
		extract($_params_, EXTR_OVERWRITE);
		require($_file_);
		return ob_get_clean();
Qiang Xue committed
371 372
	}

Qiang Xue committed
373 374 375 376 377 378 379 380 381
	/**
	 * Renders dynamic content returned by the given PHP statements.
	 * This method is mainly used together with content caching (fragment caching and page caching)
	 * when some portions of the content (called *dynamic content*) should not be cached.
	 * The dynamic content must be returned by some PHP statements.
	 * @param string $statements the PHP statements for generating the dynamic content.
	 * @return string the placeholder of the dynamic content, or the dynamic content if there is no
	 * active content cache currently.
	 */
Qiang Xue committed
382 383
	public function renderDynamic($statements)
	{
Qiang Xue committed
384 385
		if (!empty($this->cacheStack)) {
			$n = count($this->dynamicPlaceholders);
Qiang Xue committed
386
			$placeholder = "<![CDATA[YII-DYNAMIC-$n]]>";
Qiang Xue committed
387
			$this->addDynamicPlaceholder($placeholder, $statements);
Qiang Xue committed
388 389 390 391 392 393
			return $placeholder;
		} else {
			return $this->evaluateDynamicContent($statements);
		}
	}

Qiang Xue committed
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
	/**
	 * Adds a placeholder for dynamic content.
	 * This method is internally used.
	 * @param string $placeholder the placeholder name
	 * @param string $statements the PHP statements for generating the dynamic content
	 */
	public function addDynamicPlaceholder($placeholder, $statements)
	{
		foreach ($this->cacheStack as $cache) {
			$cache->dynamicPlaceholders[$placeholder] = $statements;
		}
		$this->dynamicPlaceholders[$placeholder] = $statements;
	}

	/**
	 * Evaluates the given PHP statements.
	 * This method is mainly used internally to implement dynamic content feature.
	 * @param string $statements the PHP statements to be evaluated.
	 * @return mixed the return value of the PHP statements.
	 */
Qiang Xue committed
414 415 416 417 418
	public function evaluateDynamicContent($statements)
	{
		return eval($statements);
	}

Qiang Xue committed
419
	/**
Qiang Xue committed
420
	 * Begins recording a block.
421
	 * This method is a shortcut to beginning [[Block]]
Qiang Xue committed
422 423 424
	 * @param string $id the block ID.
	 * @param boolean $renderInPlace whether to render the block content in place.
	 * Defaults to false, meaning the captured block will not be displayed.
425
	 * @return Block the Block widget instance
Qiang Xue committed
426
	 */
Qiang Xue committed
427
	public function beginBlock($id, $renderInPlace = false)
Qiang Xue committed
428
	{
Alexander Makarov committed
429
		return Block::begin([
Qiang Xue committed
430 431
			'id' => $id,
			'renderInPlace' => $renderInPlace,
432
			'view' => $this,
Alexander Makarov committed
433
		]);
Qiang Xue committed
434 435 436
	}

	/**
Qiang Xue committed
437
	 * Ends recording a block.
Qiang Xue committed
438
	 */
Qiang Xue committed
439
	public function endBlock()
Qiang Xue committed
440
	{
441
		Block::end();
Qiang Xue committed
442 443
	}

Qiang Xue committed
444 445
	/**
	 * Begins the rendering of content that is to be decorated by the specified view.
Qiang Xue committed
446
	 * This method can be used to implement nested layout. For example, a layout can be embedded
447
	 * in another layout file specified as '@app/view/layouts/base.php' like the following:
Qiang Xue committed
448 449
	 *
	 * ~~~
450
	 * <?php $this->beginContent('@app/view/layouts/base.php'); ?>
Qiang Xue committed
451 452 453 454 455 456
	 * ...layout content here...
	 * <?php $this->endContent(); ?>
	 * ~~~
	 *
	 * @param string $viewFile the view file that will be used to decorate the content enclosed by this widget.
	 * This can be specified as either the view file path or path alias.
resurtm committed
457
	 * @param array $params the variables (name => value) to be extracted and made available in the decorative view.
458 459
	 * @return ContentDecorator the ContentDecorator widget instance
	 * @see ContentDecorator
Qiang Xue committed
460
	 */
Alexander Makarov committed
461
	public function beginContent($viewFile, $params = [])
Qiang Xue committed
462
	{
Alexander Makarov committed
463
		return ContentDecorator::begin([
Qiang Xue committed
464
			'viewFile' => $viewFile,
Qiang Xue committed
465
			'params' => $params,
466
			'view' => $this,
Alexander Makarov committed
467
		]);
Qiang Xue committed
468 469 470 471 472 473 474
	}

	/**
	 * Ends the rendering of content.
	 */
	public function endContent()
	{
475
		ContentDecorator::end();
Qiang Xue committed
476 477
	}

478 479 480 481 482 483 484 485
	/**
	 * Begins fragment caching.
	 * This method will display cached content if it is available.
	 * If not, it will start caching and would expect an [[endCache()]]
	 * call to end the cache and save the content into cache.
	 * A typical usage of fragment caching is as follows,
	 *
	 * ~~~
resurtm committed
486
	 * if ($this->beginCache($id)) {
487 488 489 490 491 492
	 *     // ...generate content here
	 *     $this->endCache();
	 * }
	 * ~~~
	 *
	 * @param string $id a unique ID identifying the fragment to be cached.
493
	 * @param array $properties initial property values for [[FragmentCache]]
494 495 496
	 * @return boolean whether you should generate the content for caching.
	 * False if the cached version is available.
	 */
Alexander Makarov committed
497
	public function beginCache($id, $properties = [])
498 499
	{
		$properties['id'] = $id;
500
		$properties['view'] = $this;
501
		/** @var $cache FragmentCache */
502
		$cache = FragmentCache::begin($properties);
Qiang Xue committed
503
		if ($cache->getCachedContent() !== false) {
504 505 506 507 508 509 510 511 512 513 514 515
			$this->endCache();
			return false;
		} else {
			return true;
		}
	}

	/**
	 * Ends fragment caching.
	 */
	public function endCache()
	{
516
		FragmentCache::end();
517
	}
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546


	private $_assetManager;

	/**
	 * Registers the asset manager being used by this view object.
	 * @return \yii\web\AssetManager the asset manager. Defaults to the "assetManager" application component.
	 */
	public function getAssetManager()
	{
		return $this->_assetManager ?: Yii::$app->getAssetManager();
	}

	/**
	 * Sets the asset manager.
	 * @param \yii\web\AssetManager $value the asset manager
	 */
	public function setAssetManager($value)
	{
		$this->_assetManager = $value;
	}

	/**
	 * Marks the beginning of an HTML page.
	 */
	public function beginPage()
	{
		ob_start();
		ob_implicit_flush(false);
547 548

		$this->trigger(self::EVENT_BEGIN_PAGE);
549 550 551 552 553 554 555
	}

	/**
	 * Marks the ending of an HTML page.
	 */
	public function endPage()
	{
556 557
		$this->trigger(self::EVENT_END_PAGE);

558
		$content = ob_get_clean();
559
		foreach (array_keys($this->assetBundles) as $bundle) {
Carsten Brandt committed
560 561
			$this->registerAssetFiles($bundle);
		}
Alexander Makarov committed
562
		echo strtr($content, [
563 564 565
			self::PH_HEAD => $this->renderHeadHtml(),
			self::PH_BODY_BEGIN => $this->renderBodyBeginHtml(),
			self::PH_BODY_END => $this->renderBodyEndHtml(),
Alexander Makarov committed
566
		]);
567 568 569 570 571 572 573 574 575 576 577

		unset(
			$this->metaTags,
			$this->linkTags,
			$this->css,
			$this->cssFiles,
			$this->js,
			$this->jsFiles
		);
	}

578 579
	/**
	 * Registers all files provided by an asset bundle including depending bundles files.
580
	 * Removes a bundle from [[assetBundles]] once files are registered.
581 582 583 584 585 586 587 588
	 * @param string $name name of the bundle to register
	 */
	private function registerAssetFiles($name)
	{
		if (!isset($this->assetBundles[$name])) {
			return;
		}
		$bundle = $this->assetBundles[$name];
589
		foreach ($bundle->depends as $dep) {
590 591
			$this->registerAssetFiles($dep);
		}
592
		$bundle->registerAssetFiles($this);
593 594 595
		unset($this->assetBundles[$name]);
	}

596 597 598 599 600
	/**
	 * Marks the beginning of an HTML body section.
	 */
	public function beginBody()
	{
601
		echo self::PH_BODY_BEGIN;
Qiang Xue committed
602
		$this->trigger(self::EVENT_BEGIN_BODY);
603 604 605 606 607 608 609
	}

	/**
	 * Marks the ending of an HTML body section.
	 */
	public function endBody()
	{
Qiang Xue committed
610
		$this->trigger(self::EVENT_END_BODY);
611
		echo self::PH_BODY_END;
612 613 614 615 616 617 618
	}

	/**
	 * Marks the position of an HTML head section.
	 */
	public function head()
	{
619
		echo self::PH_HEAD;
620 621 622 623 624 625
	}

	/**
	 * Registers the named asset bundle.
	 * All dependent asset bundles will be registered.
	 * @param string $name the name of the asset bundle.
626 627 628 629
	 * @param integer|null $position if set, this forces a minimum position for javascript files.
	 * This will adjust depending assets javascript file position or fail if requirement can not be met.
	 * If this is null, asset bundles position settings will not be changed.
	 * See [[registerJsFile]] for more details on javascript position.
630
	 * @return AssetBundle the registered asset bundle instance
Qiang Xue committed
631
	 * @throws InvalidConfigException if the asset bundle does not exist or a circular dependency is detected
632
	 */
Carsten Brandt committed
633
	public function registerAssetBundle($name, $position = null)
634 635 636 637
	{
		if (!isset($this->assetBundles[$name])) {
			$am = $this->getAssetManager();
			$bundle = $am->getBundle($name);
Qiang Xue committed
638
			$this->assetBundles[$name] = false;
Carsten Brandt committed
639 640 641 642 643
			// register dependencies
			$pos = isset($bundle->jsOptions['position']) ? $bundle->jsOptions['position'] : null;
			foreach ($bundle->depends as $dep) {
				$this->registerAssetBundle($dep, $pos);
			}
Qiang Xue committed
644
			$this->assetBundles[$name] = $bundle;
645
		} elseif ($this->assetBundles[$name] === false) {
Qiang Xue committed
646
			throw new InvalidConfigException("A circular dependency is detected for bundle '$name'.");
Carsten Brandt committed
647 648 649 650 651 652 653 654 655
		} else {
			$bundle = $this->assetBundles[$name];
		}

		if ($position !== null) {
			$pos = isset($bundle->jsOptions['position']) ? $bundle->jsOptions['position'] : null;
			if ($pos === null) {
				$bundle->jsOptions['position'] = $pos = $position;
			} elseif ($pos > $position) {
Carsten Brandt committed
656
				throw new InvalidConfigException("An asset bundle that depends on '$name' has a higher javascript file position configured than '$name'.");
Carsten Brandt committed
657
			}
Carsten Brandt committed
658
			// update position for all dependencies
Carsten Brandt committed
659 660 661
			foreach ($bundle->depends as $dep) {
				$this->registerAssetBundle($dep, $pos);
			}
662
		}
Carsten Brandt committed
663
		return $bundle;
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
	}

	/**
	 * Registers a meta tag.
	 * @param array $options the HTML attributes for the meta tag.
	 * @param string $key the key that identifies the meta tag. If two meta tags are registered
	 * with the same key, the latter will overwrite the former. If this is null, the new meta tag
	 * will be appended to the existing ones.
	 */
	public function registerMetaTag($options, $key = null)
	{
		if ($key === null) {
			$this->metaTags[] = Html::tag('meta', '', $options);
		} else {
			$this->metaTags[$key] = Html::tag('meta', '', $options);
		}
	}

	/**
	 * Registers a link tag.
	 * @param array $options the HTML attributes for the link tag.
	 * @param string $key the key that identifies the link tag. If two link tags are registered
	 * with the same key, the latter will overwrite the former. If this is null, the new link tag
	 * will be appended to the existing ones.
	 */
	public function registerLinkTag($options, $key = null)
	{
		if ($key === null) {
			$this->linkTags[] = Html::tag('link', '', $options);
		} else {
			$this->linkTags[$key] = Html::tag('link', '', $options);
		}
	}

	/**
	 * Registers a CSS code block.
	 * @param string $css the CSS code block to be registered
	 * @param array $options the HTML attributes for the style tag.
	 * @param string $key the key that identifies the CSS code block. If null, it will use
	 * $css as the key. If two CSS code blocks are registered with the same key, the latter
	 * will overwrite the former.
	 */
Alexander Makarov committed
706
	public function registerCss($css, $options = [], $key = null)
707
	{
708
		$key = $key ?: md5($css);
709 710 711 712 713 714 715 716 717 718 719
		$this->css[$key] = Html::style($css, $options);
	}

	/**
	 * Registers a CSS file.
	 * @param string $url the CSS file to be registered.
	 * @param array $options the HTML attributes for the link tag.
	 * @param string $key the key that identifies the CSS script file. If null, it will use
	 * $url as the key. If two CSS files are registered with the same key, the latter
	 * will overwrite the former.
	 */
Alexander Makarov committed
720
	public function registerCssFile($url, $options = [], $key = null)
721 722 723 724 725 726 727 728
	{
		$key = $key ?: $url;
		$this->cssFiles[$key] = Html::cssFile($url, $options);
	}

	/**
	 * Registers a JS code block.
	 * @param string $js the JS code block to be registered
729 730
	 * @param integer $position the position at which the JS script tag should be inserted
	 * in a page. The possible values are:
731 732 733 734
	 *
	 * - [[POS_HEAD]]: in the head section
	 * - [[POS_BEGIN]]: at the beginning of the body section
	 * - [[POS_END]]: at the end of the body section
735
	 * - [[POS_READY]]: enclosed within jQuery(document).ready(). This is the default value.
Alexander Makarov committed
736
	 *   Note that by using this position, the method will automatically register the jQuery js file.
737 738 739 740 741
	 *
	 * @param string $key the key that identifies the JS code block. If null, it will use
	 * $js as the key. If two JS code blocks are registered with the same key, the latter
	 * will overwrite the former.
	 */
742
	public function registerJs($js, $position = self::POS_READY, $key = null)
743
	{
744
		$key = $key ?: md5($js);
745 746
		$this->js[$position][$key] = $js;
		if ($position === self::POS_READY) {
747
			JqueryAsset::register($this);
748
		}
749 750 751 752
	}

	/**
	 * Registers a JS file.
753 754
	 * Please note that when this file depends on other JS files to be registered before,
	 * for example jQuery, you should use [[registerAssetBundle]] instead.
755 756 757 758 759 760 761
	 * @param string $url the JS file to be registered.
	 * @param array $options the HTML attributes for the script tag. A special option
	 * named "position" is supported which specifies where the JS script tag should be inserted
	 * in a page. The possible values of "position" are:
	 *
	 * - [[POS_HEAD]]: in the head section
	 * - [[POS_BEGIN]]: at the beginning of the body section
762
	 * - [[POS_END]]: at the end of the body section. This is the default value.
763 764 765 766 767
	 *
	 * @param string $key the key that identifies the JS script file. If null, it will use
	 * $url as the key. If two JS files are registered with the same key, the latter
	 * will overwrite the former.
	 */
Alexander Makarov committed
768
	public function registerJsFile($url, $options = [], $key = null)
769 770 771 772 773 774 775 776 777 778 779 780 781 782
	{
		$position = isset($options['position']) ? $options['position'] : self::POS_END;
		unset($options['position']);
		$key = $key ?: $url;
		$this->jsFiles[$position][$key] = Html::jsFile($url, $options);
	}

	/**
	 * Renders the content to be inserted in the head section.
	 * The content is rendered using the registered meta tags, link tags, CSS/JS code blocks and files.
	 * @return string the rendered content
	 */
	protected function renderHeadHtml()
	{
Alexander Makarov committed
783
		$lines = [];
784
		if (!empty($this->metaTags)) {
Qiang Xue committed
785
			$lines[] = implode("\n", $this->metaTags);
786
		}
787 788

		$request = Yii::$app->getRequest();
Qiang Xue committed
789
		if ($request instanceof \yii\web\Request && $request->enableCsrfValidation) {
Alexander Makarov committed
790 791
			$lines[] = Html::tag('meta', '', ['name' => 'csrf-var', 'content' => $request->csrfVar]);
			$lines[] = Html::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]);
792 793
		}

794
		if (!empty($this->linkTags)) {
Qiang Xue committed
795
			$lines[] = implode("\n", $this->linkTags);
796 797 798 799 800 801 802 803 804 805 806
		}
		if (!empty($this->cssFiles)) {
			$lines[] = implode("\n", $this->cssFiles);
		}
		if (!empty($this->css)) {
			$lines[] = implode("\n", $this->css);
		}
		if (!empty($this->jsFiles[self::POS_HEAD])) {
			$lines[] = implode("\n", $this->jsFiles[self::POS_HEAD]);
		}
		if (!empty($this->js[self::POS_HEAD])) {
Alexander Makarov committed
807
			$lines[] = Html::script(implode("\n", $this->js[self::POS_HEAD]), ['type' => 'text/javascript']);
808
		}
Qiang Xue committed
809
		return empty($lines) ? '' : implode("\n", $lines);
810 811 812 813 814 815 816 817 818
	}

	/**
	 * Renders the content to be inserted at the beginning of the body section.
	 * The content is rendered using the registered JS code blocks and files.
	 * @return string the rendered content
	 */
	protected function renderBodyBeginHtml()
	{
Alexander Makarov committed
819
		$lines = [];
820 821 822 823
		if (!empty($this->jsFiles[self::POS_BEGIN])) {
			$lines[] = implode("\n", $this->jsFiles[self::POS_BEGIN]);
		}
		if (!empty($this->js[self::POS_BEGIN])) {
Alexander Makarov committed
824
			$lines[] = Html::script(implode("\n", $this->js[self::POS_BEGIN]), ['type' => 'text/javascript']);
825
		}
Qiang Xue committed
826
		return empty($lines) ? '' : implode("\n", $lines);
827 828 829 830 831 832 833 834 835
	}

	/**
	 * Renders the content to be inserted at the end of the body section.
	 * The content is rendered using the registered JS code blocks and files.
	 * @return string the rendered content
	 */
	protected function renderBodyEndHtml()
	{
Alexander Makarov committed
836
		$lines = [];
837 838 839 840
		if (!empty($this->jsFiles[self::POS_END])) {
			$lines[] = implode("\n", $this->jsFiles[self::POS_END]);
		}
		if (!empty($this->js[self::POS_END])) {
Alexander Makarov committed
841
			$lines[] = Html::script(implode("\n", $this->js[self::POS_END]), ['type' => 'text/javascript']);
842 843
		}
		if (!empty($this->js[self::POS_READY])) {
844
			$js = "jQuery(document).ready(function(){\n" . implode("\n", $this->js[self::POS_READY]) . "\n});";
Alexander Makarov committed
845
			$lines[] = Html::script($js, ['type' => 'text/javascript']);
846
		}
Qiang Xue committed
847
		return empty($lines) ? '' : implode("\n", $lines);
848
	}
Zander Baldwin committed
849
}