View.php 25.3 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\base\Application;
Qiang Xue committed
12
use yii\helpers\FileHelper;
13
use yii\helpers\Html;
Qiang Xue committed
14

Qiang Xue committed
15
/**
Qiang Xue committed
16
 * View represents a view object in the MVC pattern.
Qiang Xue committed
17
 *
Qiang Xue committed
18
 * View provides a set of methods (e.g. [[render()]]) for rendering purpose.
Qiang Xue committed
19
 *
Qiang Xue committed
20 21 22 23 24
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class View extends Component
{
25 26 27 28 29 30 31 32
	/**
	 * @event ViewEvent an event that is triggered by [[beginPage()]].
	 */
	const EVENT_BEGIN_PAGE = 'beginPage';
	/**
	 * @event ViewEvent an event that is triggered by [[endPage()]].
	 */
	const EVENT_END_PAGE = 'endPage';
33
	/**
34
	 * @event ViewEvent an event that is triggered by [[renderFile()]] right before it renders a view file.
35 36 37
	 */
	const EVENT_BEFORE_RENDER = 'beforeRender';
	/**
38
	 * @event ViewEvent an event that is triggered by [[renderFile()]] right after it renders a view file.
39 40 41
	 */
	const EVENT_AFTER_RENDER = 'afterRender';

Qiang Xue committed
42
	/**
43 44
	 * The location of registered JavaScript code block or files.
	 * This means the location is in the head section.
Qiang Xue committed
45
	 */
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
	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;
	/**
	 * This is internally used as the placeholder for receiving the content registered for the head section.
	 */
	const PL_HEAD = '<![CDATA[YII-BLOCK-HEAD]]>';
	/**
	 * This is internally used as the placeholder for receiving the content registered for the beginning of the body section.
	 */
	const PL_BODY_BEGIN = '<![CDATA[YII-BLOCK-BODY-BEGIN]]>';
Qiang Xue committed
65
	/**
66
	 * This is internally used as the placeholder for receiving the content registered for the end of the body section.
Qiang Xue committed
67
	 */
68 69 70 71 72 73 74 75
	const PL_BODY_END = '<![CDATA[YII-BLOCK-BODY-END]]>';


	/**
	 * @var object the context under which the [[renderFile()]] method is being invoked.
	 * This can be a controller, a widget, or any other object.
	 */
	public $context;
Qiang Xue committed
76
	/**
Qiang Xue committed
77
	 * @var mixed custom parameters that are shared among view templates.
Qiang Xue committed
78
	 */
Qiang Xue committed
79
	public $params;
Qiang Xue committed
80
	/**
Qiang Xue committed
81 82
	 * @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.
83 84 85
	 * The default setting supports both Smarty and Twig (their corresponding file extension is "tpl"
	 * and "twig" respectively. Please refer to [[SmartyRenderer]] and [[TwigRenderer]] on how to install
	 * the needed libraries for these template engines.
Qiang Xue committed
86 87 88
	 *
	 * 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
89
	 */
90 91 92 93 94 95 96 97
	public $renderers = array(
		'tpl' => array(
			'class' => 'yii\renderers\SmartyRenderer',
		),
		'twig' => array(
			'class' => 'yii\renderers\TwigRenderer',
		),
	);
98
	/**
99
	 * @var Theme|array the theme object or the configuration array for creating the theme object.
Qiang Xue committed
100
	 * If not set, it means theming is not enabled.
101
	 */
Qiang Xue committed
102
	public $theme;
Qiang Xue committed
103
	/**
Qiang Xue committed
104 105
	 * @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()]]
106
	 * to capture small fragments of a view. They can be later accessed somewhere else
Qiang Xue committed
107 108
	 * through this property.
	 */
Qiang Xue committed
109
	public $blocks;
Qiang Xue committed
110
	/**
Qiang Xue committed
111
	 * @var Widget[] the widgets that are currently being rendered (not ended). This property
112 113
	 * is maintained by [[beginWidget()]] and [[endWidget()]] methods. Do not modify it directly.
	 * @internal
Qiang Xue committed
114 115 116 117
	 */
	public $widgetStack = array();
	/**
	 * @var array a list of currently active fragment cache widgets. This property
118 119
	 * is used internally to implement the content caching feature. Do not modify it directly.
	 * @internal
Qiang Xue committed
120 121 122 123
	 */
	public $cacheStack = array();
	/**
	 * @var array a list of placeholders for embedding dynamic contents. This property
124 125
	 * is used internally to implement the content caching feature. Do not modify it directly.
	 * @internal
Qiang Xue committed
126
	 */
Qiang Xue committed
127
	public $dynamicPlaceholders = array();
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
	/**
	 * @var array the registered asset bundles. The keys are the bundle names, and the values
	 * are the corresponding [[AssetBundle]] objects.
	 * @see registerAssetBundle
	 */
	public $assetBundles;
	/**
	 * @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
168 169


Qiang Xue committed
170
	/**
Qiang Xue committed
171
	 * Initializes the view component.
Qiang Xue committed
172
	 */
Qiang Xue committed
173
	public function init()
Qiang Xue committed
174
	{
Qiang Xue committed
175 176 177
		parent::init();
		if (is_array($this->theme)) {
			$this->theme = Yii::createObject($this->theme);
Qiang Xue committed
178 179 180
		}
	}

Qiang Xue committed
181
	/**
Qiang Xue committed
182
	 * Renders a view.
Qiang Xue committed
183
	 *
Qiang Xue committed
184
	 * This method delegates the call to the [[context]] object:
Qiang Xue committed
185
	 *
Qiang Xue committed
186 187 188 189 190 191
	 * - If [[context]] is a controller, the [[Controller::renderPartial()]] method will be called;
	 * - If [[context]] is a widget, the [[Widget::render()]] method will be called;
	 * - Otherwise, an InvalidCallException exception will be thrown.
	 *
	 * @param string $view the view name. Please refer to [[Controller::findViewFile()]]
	 * and [[Widget::findViewFile()]] on how to specify this parameter.
Qiang Xue committed
192
	 * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
193
	 * @return string the rendering result
Qiang Xue committed
194
	 * @throws InvalidCallException if [[context]] is neither a controller nor a widget.
Qiang Xue committed
195 196
	 * @throws InvalidParamException if the view cannot be resolved or the view file does not exist.
	 * @see renderFile
Qiang Xue committed
197
	 */
Qiang Xue committed
198
	public function render($view, $params = array())
Qiang Xue committed
199
	{
Qiang Xue committed
200 201 202 203 204 205 206
		if ($this->context instanceof Controller) {
			return $this->context->renderPartial($view, $params);
		} elseif ($this->context instanceof Widget) {
			return $this->context->render($view, $params);
		} else {
			throw new InvalidCallException('View::render() is not supported for the current context.');
		}
Qiang Xue committed
207 208
	}

Qiang Xue committed
209 210
	/**
	 * Renders a view file.
Qiang Xue committed
211
	 *
Qiang Xue committed
212 213
	 * 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
214
	 *
Qiang Xue committed
215 216 217 218 219 220
	 * 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
221
	 * @param string $viewFile the view file. This can be either a file path or a path alias.
Qiang Xue committed
222
	 * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
Qiang Xue committed
223 224
	 * @param object $context the context that the view should use for rendering the view. If null,
	 * existing [[context]] will be used.
Qiang Xue committed
225
	 * @return string the rendering result
Qiang Xue committed
226
	 * @throws InvalidParamException if the view file does not exist
Qiang Xue committed
227
	 */
Qiang Xue committed
228
	public function renderFile($viewFile, $params = array(), $context = null)
Qiang Xue committed
229
	{
Qiang Xue committed
230 231 232 233 234 235 236 237 238 239
		$viewFile = Yii::getAlias($viewFile);
		if (is_file($viewFile)) {
			if ($this->theme !== null) {
				$viewFile = $this->theme->applyTo($viewFile);
			}
			$viewFile = FileHelper::localize($viewFile);
		} else {
			throw new InvalidParamException("The view file does not exist: $viewFile");
		}

Qiang Xue committed
240
		$oldContext = $this->context;
Qiang Xue committed
241 242 243
		if ($context !== null) {
			$this->context = $context;
		}
Qiang Xue committed
244

245 246
		$output = '';
		if ($this->beforeRender($viewFile)) {
Qiang Xue committed
247 248 249 250 251 252 253 254
			$ext = pathinfo($viewFile, PATHINFO_EXTENSION);
			if (isset($this->renderers[$ext])) {
				if (is_array($this->renderers[$ext])) {
					$this->renderers[$ext] = Yii::createObject($this->renderers[$ext]);
				}
				/** @var ViewRenderer $renderer */
				$renderer = $this->renderers[$ext];
				$output = $renderer->render($this, $viewFile, $params);
255 256 257 258
			} else {
				$output = $this->renderPhpFile($viewFile, $params);
			}
			$this->afterRender($viewFile, $output);
Qiang Xue committed
259
		}
Qiang Xue committed
260 261 262 263

		$this->context = $oldContext;

		return $output;
Qiang Xue committed
264 265
	}

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
	/**
	 * 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
298
	/**
Qiang Xue committed
299 300 301 302 303 304
	 * 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
305 306
	 * This method should mainly be called by view renderer or [[renderFile()]].
	 *
Qiang Xue committed
307 308 309
	 * @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
310
	 */
Qiang Xue committed
311
	public function renderPhpFile($_file_, $_params_ = array())
Qiang Xue committed
312
	{
Qiang Xue committed
313 314 315 316 317
		ob_start();
		ob_implicit_flush(false);
		extract($_params_, EXTR_OVERWRITE);
		require($_file_);
		return ob_get_clean();
Qiang Xue committed
318 319
	}

Qiang Xue committed
320 321 322 323 324 325 326 327 328
	/**
	 * 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
329 330
	public function renderDynamic($statements)
	{
Qiang Xue committed
331 332
		if (!empty($this->cacheStack)) {
			$n = count($this->dynamicPlaceholders);
Qiang Xue committed
333
			$placeholder = "<![CDATA[YII-DYNAMIC-$n]]>";
Qiang Xue committed
334
			$this->addDynamicPlaceholder($placeholder, $statements);
Qiang Xue committed
335 336 337 338 339 340
			return $placeholder;
		} else {
			return $this->evaluateDynamicContent($statements);
		}
	}

Qiang Xue committed
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
	/**
	 * 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
361 362 363 364 365
	public function evaluateDynamicContent($statements)
	{
		return eval($statements);
	}

Qiang Xue committed
366 367 368 369 370 371 372
	/**
	 * Creates a widget.
	 * This method will use [[Yii::createObject()]] to create the widget.
	 * @param string $class the widget class name or path alias
	 * @param array $properties the initial property values of the widget.
	 * @return Widget the newly created widget instance
	 */
Qiang Xue committed
373 374 375
	public function createWidget($class, $properties = array())
	{
		$properties['class'] = $class;
Qiang Xue committed
376 377 378
		if (!isset($properties['view'])) {
			$properties['view'] = $this;
		}
Qiang Xue committed
379
		return Yii::createObject($properties);
Qiang Xue committed
380 381
	}

Qiang Xue committed
382 383 384 385 386 387 388 389 390 391
	/**
	 * Creates and runs a widget.
	 * Compared with [[createWidget()]], this method does one more thing: it will
	 * run the widget after it is created.
	 * @param string $class the widget class name or path alias
	 * @param array $properties the initial property values of the widget.
	 * @param boolean $captureOutput whether to capture the output of the widget and return it as a string
	 * @return string|Widget if $captureOutput is true, the output of the widget will be returned;
	 * otherwise the widget object will be returned.
	 */
Qiang Xue committed
392
	public function widget($class, $properties = array(), $captureOutput = false)
Qiang Xue committed
393
	{
Qiang Xue committed
394 395 396 397 398 399 400 401 402 403 404
		if ($captureOutput) {
			ob_start();
			ob_implicit_flush(false);
			$widget = $this->createWidget($class, $properties);
			$widget->run();
			return ob_get_clean();
		} else {
			$widget = $this->createWidget($class, $properties);
			$widget->run();
			return $widget;
		}
Qiang Xue committed
405 406
	}

Qiang Xue committed
407 408
	/**
	 * Begins a widget.
Qiang Xue committed
409 410 411 412
	 * This method is similar to [[createWidget()]] except that it will expect a matching
	 * [[endWidget()]] call after this.
	 * @param string $class the widget class name or path alias
	 * @param array $properties the initial property values of the widget.
Qiang Xue committed
413 414
	 * @return Widget the widget instance
	 */
Qiang Xue committed
415 416
	public function beginWidget($class, $properties = array())
	{
417
		$widget = $this->createWidget($class, $properties);
Qiang Xue committed
418
		$this->widgetStack[] = $widget;
419
		return $widget;
Qiang Xue committed
420 421
	}

Qiang Xue committed
422 423 424 425 426 427
	/**
	 * Ends a widget.
	 * Note that the rendering result of the widget is directly echoed out.
	 * If you want to capture the rendering result of a widget, you may use
	 * [[createWidget()]] and [[Widget::run()]].
	 * @return Widget the widget instance
Qiang Xue committed
428
	 * @throws InvalidCallException if [[beginWidget()]] and [[endWidget()]] calls are not properly nested
Qiang Xue committed
429
	 */
Qiang Xue committed
430
	public function endWidget()
Qiang Xue committed
431
	{
Qiang Xue committed
432
		$widget = array_pop($this->widgetStack);
Qiang Xue committed
433
		if ($widget instanceof Widget) {
Qiang Xue committed
434
			$widget->run();
Qiang Xue committed
435
			return $widget;
436
		} else {
Qiang Xue committed
437
			throw new InvalidCallException("Unmatched beginWidget() and endWidget() calls.");
Qiang Xue committed
438 439 440
		}
	}

Qiang Xue committed
441
	/**
Qiang Xue committed
442 443 444 445 446 447
	 * Begins recording a block.
	 * This method is a shortcut to beginning [[yii\widgets\Block]]
	 * @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.
	 * @return \yii\widgets\Block the Block widget instance
Qiang Xue committed
448
	 */
Qiang Xue committed
449
	public function beginBlock($id, $renderInPlace = false)
Qiang Xue committed
450
	{
Qiang Xue committed
451
		return $this->beginWidget('yii\widgets\Block', array(
Qiang Xue committed
452 453 454 455 456 457
			'id' => $id,
			'renderInPlace' => $renderInPlace,
		));
	}

	/**
Qiang Xue committed
458
	 * Ends recording a block.
Qiang Xue committed
459
	 */
Qiang Xue committed
460
	public function endBlock()
Qiang Xue committed
461 462 463 464
	{
		$this->endWidget();
	}

Qiang Xue committed
465 466
	/**
	 * Begins the rendering of content that is to be decorated by the specified view.
Qiang Xue committed
467 468 469 470 471 472 473 474 475 476 477
	 * This method can be used to implement nested layout. For example, a layout can be embedded
	 * in another layout file specified as '@app/view/layouts/base' like the following:
	 *
	 * ~~~
	 * <?php $this->beginContent('@app/view/layouts/base'); ?>
	 * ...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.
Qiang Xue committed
478 479 480 481
	 * @param array $params the variables (name=>value) to be extracted and made available in the decorative view.
	 * @return \yii\widgets\ContentDecorator the ContentDecorator widget instance
	 * @see \yii\widgets\ContentDecorator
	 */
Qiang Xue committed
482
	public function beginContent($viewFile, $params = array())
Qiang Xue committed
483 484
	{
		return $this->beginWidget('yii\widgets\ContentDecorator', array(
Qiang Xue committed
485
			'viewFile' => $viewFile,
Qiang Xue committed
486 487 488 489 490 491 492 493 494 495 496 497
			'params' => $params,
		));
	}

	/**
	 * Ends the rendering of content.
	 */
	public function endContent()
	{
		$this->endWidget();
	}

498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
	/**
	 * 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,
	 *
	 * ~~~
	 * if($this->beginCache($id)) {
	 *     // ...generate content here
	 *     $this->endCache();
	 * }
	 * ~~~
	 *
	 * @param string $id a unique ID identifying the fragment to be cached.
Qiang Xue committed
513
	 * @param array $properties initial property values for [[\yii\widgets\FragmentCache]]
514 515 516 517 518 519
	 * @return boolean whether you should generate the content for caching.
	 * False if the cached version is available.
	 */
	public function beginCache($id, $properties = array())
	{
		$properties['id'] = $id;
Qiang Xue committed
520
		/** @var $cache \yii\widgets\FragmentCache */
Qiang Xue committed
521
		$cache = $this->beginWidget('yii\widgets\FragmentCache', $properties);
Qiang Xue committed
522
		if ($cache->getCachedContent() !== false) {
523 524 525 526 527 528 529 530 531 532 533 534 535 536
			$this->endCache();
			return false;
		} else {
			return true;
		}
	}

	/**
	 * Ends fragment caching.
	 */
	public function endCache()
	{
		$this->endWidget();
	}
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565


	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);
566 567

		$this->trigger(self::EVENT_BEGIN_PAGE);
568 569 570 571 572 573 574
	}

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

577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
		$content = ob_get_clean();
		echo strtr($content, array(
			self::PL_HEAD => $this->renderHeadHtml(),
			self::PL_BODY_BEGIN => $this->renderBodyBeginHtml(),
			self::PL_BODY_END => $this->renderBodyEndHtml(),
		));

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

	/**
	 * Marks the beginning of an HTML body section.
	 */
	public function beginBody()
	{
		echo self::PL_BODY_BEGIN;
	}

	/**
	 * Marks the ending of an HTML body section.
	 */
	public function endBody()
	{
		echo self::PL_BODY_END;
	}

	/**
	 * Marks the position of an HTML head section.
	 */
	public function head()
	{
		echo self::PL_HEAD;
	}

	/**
	 * Registers the named asset bundle.
	 * All dependent asset bundles will be registered.
	 * @param string $name the name of the asset bundle.
Qiang Xue committed
623
	 * @throws InvalidConfigException if the asset bundle does not exist or a circular dependency is detected
624 625 626 627 628 629 630 631 632 633 634 635 636 637
	 */
	public function registerAssetBundle($name)
	{
		if (!isset($this->assetBundles[$name])) {
			$am = $this->getAssetManager();
			$bundle = $am->getBundle($name);
			if ($bundle !== null) {
				$this->assetBundles[$name] = false;
				$bundle->registerAssets($this);
				$this->assetBundles[$name] = true;
			} else {
				throw new InvalidConfigException("Unknown asset bundle: $name");
			}
		} elseif ($this->assetBundles[$name] === false) {
Qiang Xue committed
638
			throw new InvalidConfigException("A circular dependency is detected for bundle '$name'.");
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 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 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
		}
	}

	/**
	 * 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.
	 */
	public function registerCss($css, $options = array(), $key = null)
	{
		$key = $key ?: $css;
		$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.
	 */
	public function registerCssFile($url, $options = array(), $key = null)
	{
		$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
	 * @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
	 * - [[POS_END]]: at the end of the body section
	 *
	 * @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.
	 */
	public function registerJs($js, $options = array(), $key = null)
	{
		$position = isset($options['position']) ? $options['position'] : self::POS_END;
		unset($options['position']);
		$key = $key ?: $js;
		$this->js[$position][$key] = Html::script($js, $options);
	}

	/**
	 * Registers a JS file.
	 * @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
	 * - [[POS_END]]: at the end of the body section
	 *
	 * @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.
	 */
	public function registerJsFile($url, $options = array(), $key = null)
	{
		$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()
	{
		$lines = array();
		if (!empty($this->metaTags)) {
Qiang Xue committed
757
			$lines[] = implode("\n", $this->metaTags);
758 759
		}
		if (!empty($this->linkTags)) {
Qiang Xue committed
760
			$lines[] = implode("\n", $this->linkTags);
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
		}
		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])) {
			$lines[] = implode("\n", $this->js[self::POS_HEAD]);
		}
		return implode("\n", $lines);
	}

	/**
	 * 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()
	{
		$lines = array();
		if (!empty($this->jsFiles[self::POS_BEGIN])) {
			$lines[] = implode("\n", $this->jsFiles[self::POS_BEGIN]);
		}
		if (!empty($this->js[self::POS_BEGIN])) {
			$lines[] = implode("\n", $this->js[self::POS_BEGIN]);
		}
		return implode("\n", $lines);
	}

	/**
	 * 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()
	{
		$lines = array();
		if (!empty($this->jsFiles[self::POS_END])) {
			$lines[] = implode("\n", $this->jsFiles[self::POS_END]);
		}
		if (!empty($this->js[self::POS_END])) {
			$lines[] = implode("\n", $this->js[self::POS_END]);
		}
		return implode("\n", $lines);
	}
Zander Baldwin committed
810
}