View.php 16.8 KB
Newer Older
Qiang Xue committed
1 2 3 4 5
<?php
/**
 * View class file.
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008 Yii Software LLC
Qiang Xue committed
7 8 9 10 11
 * @license http://www.yiiframework.com/license/
 */

namespace yii\base;

Qiang Xue committed
12
use Yii;
Qiang Xue committed
13
use yii\util\FileHelper;
Qiang Xue committed
14
use yii\base\Application;
Qiang Xue committed
15

Qiang Xue committed
16
/**
Qiang Xue committed
17 18 19 20
 * View represents a view object in the MVC pattern.
 * 
 * View provides a set of methods (e.g. [[render()]]) for rendering purpose.
 * 
Qiang Xue committed
21 22 23 24 25
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class View extends Component
{
Qiang Xue committed
26
	/**
Qiang Xue committed
27 28 29 30
	 * @var object the object that owns this view. This can be a controller, a widget, or any other object.
	 */
	public $owner;
	/**
Qiang Xue committed
31 32
	 * @var string the layout to be applied when [[render()]] or [[renderContent()]] is called.
	 * If not set, it will use the [[Module::layout]] of the currently active module.
Qiang Xue committed
33
	 */
Qiang Xue committed
34
	public $layout;
Qiang Xue committed
35 36 37 38 39 40 41 42 43 44
	/**
	 * @var string the language that the view should be rendered in. If not set, it will use
	 * the value of [[Application::language]].
	 */
	public $language;
	/**
	 * @var string the language that the original view is in. If not set, it will use
	 * the value of [[Application::sourceLanguage]].
	 */
	public $sourceLanguage;
Qiang Xue committed
45 46 47 48 49
	/**
	 * @var boolean whether to localize the view when possible. Defaults to true.
	 * Note that when this is true, if a localized view cannot be found, the original view will be rendered.
	 * No error will be reported.
	 */
Qiang Xue committed
50
	public $enableI18N = true;
Qiang Xue committed
51 52
	/**
	 * @var boolean whether to theme the view when possible. Defaults to true.
Qiang Xue committed
53
	 * Note that theming will be disabled if [[Application::theme]] is not set.
Qiang Xue committed
54
	 */
Qiang Xue committed
55
	public $enableTheme = true;
56 57 58 59
	/**
	 * @var mixed custom parameters that are available in the view template
	 */
	public $params;
Qiang Xue committed
60

Qiang Xue committed
61 62 63
	/**
	 * @var Widget[] the widgets that are currently not ended
	 */
Qiang Xue committed
64
	private  $_widgetStack = array();
Qiang Xue committed
65

Qiang Xue committed
66 67
	/**
	 * Constructor.
Qiang Xue committed
68
	 * @param object $owner the owner of this view. This usually is a controller or a widget.
Qiang Xue committed
69
	 * @param array $config name-value pairs that will be used to initialize the object properties
Qiang Xue committed
70
	 */
Qiang Xue committed
71
	public function __construct($owner, $config = array())
Qiang Xue committed
72
	{
Qiang Xue committed
73
		$this->owner = $owner;
Qiang Xue committed
74
		parent::__construct($config);
Qiang Xue committed
75 76
	}

Qiang Xue committed
77
	/**
Qiang Xue committed
78 79
	 * Renders a view within a layout.
	 * This method is similar to [[renderPartial()]] except that if a layout is available,
Qiang Xue committed
80
	 * this method will embed the view result into the layout and then return it.
Qiang Xue committed
81
	 * @param string $view the view to be rendered. Please refer to [[findViewFile()]] on possible formats of the view name.
Qiang Xue committed
82 83 84
	 * @param array $params the parameters that should be made available in the view. The PHP function `extract()`
	 * will be called on this variable to extract the variables from this parameter.
	 * @return string the rendering result
Qiang Xue committed
85 86 87
	 * @throws InvalidConfigException if the view file or layout file cannot be found
	 * @see findViewFile()
	 * @see findLayoutFile()
Qiang Xue committed
88
	 */
Qiang Xue committed
89 90 91
	public function render($view, $params = array())
	{
		$content = $this->renderPartial($view, $params);
Qiang Xue committed
92
		return $this->renderContent($content);
Qiang Xue committed
93 94
	}

Qiang Xue committed
95
	/**
Qiang Xue committed
96 97 98
	 * Renders a text content within a layout.
	 * The layout being used is resolved by [[findLayout()]].
	 * If no layout is available, the content will be returned back.
Qiang Xue committed
99 100
	 * @param string $content the content to be rendered
	 * @return string the rendering result
Qiang Xue committed
101 102
	 * @throws InvalidConfigException if the layout file cannot be found
	 * @see findLayoutFile()
Qiang Xue committed
103 104
	 */
	public function renderContent($content)
Qiang Xue committed
105 106 107
	{
		$layoutFile = $this->findLayoutFile();
		if ($layoutFile !== false) {
Qiang Xue committed
108
			return $this->renderFile($layoutFile, array('content' => $content));
Qiang Xue committed
109
		} else {
Qiang Xue committed
110
			return $content;
Qiang Xue committed
111 112 113
		}
	}

Qiang Xue committed
114 115 116
	/**
	 * Renders a view.
	 *
Qiang Xue committed
117
	 * The method first finds the actual view file corresponding to the specified view.
Qiang Xue committed
118 119 120
	 * It then calls [[renderFile()]] to render the view file. The rendering result is returned
	 * as a string. If the view file does not exist, an exception will be thrown.
	 *
Qiang Xue committed
121
	 * @param string $view the view to be rendered. Please refer to [[findViewFile()]] on possible formats of the view name.
Qiang Xue committed
122 123
	 * @param array $params the parameters that should be made available in the view. The PHP function `extract()`
	 * will be called on this variable to extract the variables from this parameter.
124
	 * @return string the rendering result
Qiang Xue committed
125
	 * @throws InvalidCallException if the view file cannot be found
Qiang Xue committed
126
	 * @see findViewFile()
Qiang Xue committed
127
	 */
Qiang Xue committed
128
	public function renderPartial($view, $params = array())
Qiang Xue committed
129 130 131
	{
		$file = $this->findViewFile($view);
		if ($file !== false) {
Qiang Xue committed
132
			return $this->renderFile($file, $params);
Qiang Xue committed
133
		} else {
Qiang Xue committed
134
			throw new InvalidCallException("Unable to find the view file for view '$view'.");
Qiang Xue committed
135 136 137
		}
	}

Qiang Xue committed
138 139
	/**
	 * Renders a view file.
Qiang Xue committed
140 141 142 143
	 * This method will extract the given parameters and include the view file.
	 * It captures the output of the included view file and returns it as a string.
	 * @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.
Qiang Xue committed
144 145
	 * @return string the rendering result
	 */
Qiang Xue committed
146
	public function renderFile($_file_, $_params_ = array())
Qiang Xue committed
147
	{
Qiang Xue committed
148 149 150 151 152
		ob_start();
		ob_implicit_flush(false);
		extract($_params_, EXTR_OVERWRITE);
		require($_file_);
		return ob_get_clean();
Qiang Xue committed
153 154
	}

Qiang Xue committed
155 156 157 158 159 160 161
	/**
	 * 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
162 163 164
	public function createWidget($class, $properties = array())
	{
		$properties['class'] = $class;
Qiang Xue committed
165
		return Yii::createObject($properties, $this->owner);
Qiang Xue committed
166 167
	}

Qiang Xue committed
168 169 170 171 172 173 174 175 176 177
	/**
	 * 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
178
	public function widget($class, $properties = array(), $captureOutput = false)
Qiang Xue committed
179
	{
Qiang Xue committed
180 181 182 183 184 185 186 187 188 189 190
		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
191 192
	}

Qiang Xue committed
193 194
	/**
	 * Begins a widget.
Qiang Xue committed
195 196 197 198
	 * 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
199 200
	 * @return Widget the widget instance
	 */
Qiang Xue committed
201 202
	public function beginWidget($class, $properties = array())
	{
203
		$widget = $this->createWidget($class, $properties);
Qiang Xue committed
204
		$this->_widgetStack[] = $widget;
205
		return $widget;
Qiang Xue committed
206 207
	}

Qiang Xue committed
208 209 210 211 212 213 214 215
	/**
	 * 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
	 * @throws Exception if [[beginWidget()]] and [[endWidget()]] calls are not properly nested
	 */
Qiang Xue committed
216
	public function endWidget()
Qiang Xue committed
217
	{
Qiang Xue committed
218 219
		$widget = array_pop($this->_widgetStack);
		if ($widget instanceof Widget) {
Qiang Xue committed
220
			$widget->run();
Qiang Xue committed
221
			return $widget;
222 223 224 225
		} else {
			throw new Exception("Unmatched beginWidget() and endWidget() calls.");
		}
	}
Qiang Xue committed
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 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 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
//
//	/**
//	 * Begins recording a clip.
//	 * This method is a shortcut to beginning [[yii\widgets\Clip]]
//	 * @param string $id the clip ID.
//	 * @param array $properties initial property values for [[yii\widgets\Clip]]
//	 */
//	public function beginClip($id, $properties = array())
//	{
//		$properties['id'] = $id;
//		$this->beginWidget('yii\widgets\Clip', $properties);
//	}
//
//	/**
//	 * Ends recording a clip.
//	 */
//	public function endClip()
//	{
//		$this->endWidget();
//	}
//
//	/**
//	 * 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.
//	 * @param array $properties initial property values for [[yii\widgets\OutputCache]]
//	 * @return boolean whether we need to generate content for caching. False if cached version is available.
//	 * @see endCache
//	 */
//	public function beginCache($id, $properties = array())
//	{
//		$properties['id'] = $id;
//		$cache = $this->beginWidget('yii\widgets\OutputCache', $properties);
//		if ($cache->getIsContentCached()) {
//			$this->endCache();
//			return false;
//		} else {
//			return true;
//		}
//	}
//
//	/**
//	 * Ends fragment caching.
//	 * This is an alias to [[endWidget()]]
//	 * @see beginCache
//	 */
//	public function endCache()
//	{
//		$this->endWidget();
//	}
//
//	/**
//	 * Begins the rendering of content that is to be decorated by the specified view.
//	 * @param mixed $view the name of the view that will be used to decorate the content. The actual view script
//	 * is resolved via {@link getViewFile}. If this parameter is null (default),
//	 * the default layout will be used as the decorative view.
//	 * Note that if the current controller does not belong to
//	 * any module, the default layout refers to the application's {@link CWebApplication::layout default layout};
//	 * If the controller belongs to a module, the default layout refers to the module's
//	 * {@link CWebModule::layout default layout}.
//	 * @param array $params the variables (name=>value) to be extracted and made available in the decorative view.
//	 * @see endContent
//	 * @see yii\widgets\ContentDecorator
//	 */
//	public function beginContent($view, $params = array())
//	{
//		$this->beginWidget('yii\widgets\ContentDecorator', array(
//			'view' => $view,
//			'params' => $params,
//		));
//	}
//
//	/**
//	 * Ends the rendering of content.
//	 * @see beginContent
//	 */
//	public function endContent()
//	{
//		$this->endWidget();
//	}
Qiang Xue committed
317

Qiang Xue committed
318 319
	/**
	 * Finds the view file based on the given view name.
Qiang Xue committed
320
	 *
Qiang Xue committed
321 322 323 324 325 326 327 328 329 330 331 332
	 * A view name can be specified in one of the following formats:
	 *
	 * - path alias (e.g. "@application/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 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 the currently
	 *   active module.
	 * - relative path (e.g. "index"): the actual view file will be looked for under the [[owner]]'s view path.
	 *   If [[owner]] is a widget or a controller, its view path is given by their `viewPath` property.
	 *   If [[owner]] is an object of any other type, its view path is the `view` sub-directory of the directory
	 *   containing the owner class file.
Qiang Xue committed
333
	 *
Qiang Xue committed
334
	 * If the view name does not contain a file extension, it will default to `.php`.
Qiang Xue committed
335 336 337 338
	 *
	 * If [[enableTheme]] is true and there is an active application them, the method will also
	 * attempt to use a themed version of the view file, when available.
	 *
Qiang Xue committed
339 340 341
	 * And if [[enableI18N]] is true, the method will attempt to use a translated version of the view file,
	 * when available.
	 *
Qiang Xue committed
342 343
	 * @param string $view the view name or path alias. If the view name does not specify
	 * the view file extension name, it will use `.php` as the extension name.
Qiang Xue committed
344 345
	 * @return string the view file path if it exists. False if the view file cannot be found.
	 * @throws InvalidConfigException if the view file does not exist
Qiang Xue committed
346
	 */
Qiang Xue committed
347
	public function findViewFile($view)
Qiang Xue committed
348
	{
Qiang Xue committed
349
		if (FileHelper::getExtension($view) === '') {
Qiang Xue committed
350
			$view .= '.php';
Qiang Xue committed
351
		}
Qiang Xue committed
352
		if (strncmp($view, '@', 1) === 0) {
Qiang Xue committed
353
			// e.g. "@application/views/common"
Qiang Xue committed
354 355 356
			if (($file = Yii::getAlias($view)) === false) {
				throw new InvalidConfigException("Invalid path alias: $view");
			}
Qiang Xue committed
357
		} elseif (strncmp($view, '/', 1) !== 0) {
Qiang Xue committed
358
			// e.g. "index"
Qiang Xue committed
359 360 361 362 363
			if ($this->owner instanceof Controller || $this->owner instanceof Widget) {
				$file = $this->owner->getViewPath() . DIRECTORY_SEPARATOR . $view;
			} elseif ($this->owner !== null) {
				$class = new \ReflectionClass($this->owner);
				$file = dirname($class->getFileName()) . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . $view;
Qiang Xue committed
364
			} else {
Qiang Xue committed
365
				$file = Yii::$application->getViewPath() . DIRECTORY_SEPARATOR . $view;
Qiang Xue committed
366
			}
Qiang Xue committed
367 368 369
		} elseif (strncmp($view, '//', 2) !== 0 && Yii::$application->controller !== null) {
			// e.g. "/site/index"
			$file = Yii::$application->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
Qiang Xue committed
370
		} else {
Qiang Xue committed
371 372
			// e.g. "//layouts/main"
			$file = Yii::$application->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
Qiang Xue committed
373 374
		}

Qiang Xue committed
375 376 377 378 379
		if (is_file($file)) {
			if ($this->enableTheme && ($theme = Yii::$application->getTheme()) !== null) {
				$file = $theme->apply($file);
			}
			return $this->enableI18N ? FileHelper::localize($file, $this->language, $this->sourceLanguage) : $file;
Qiang Xue committed
380
		} else {
Qiang Xue committed
381
			throw new InvalidConfigException("View file for view '$view' does not exist: $file");
Qiang Xue committed
382 383 384 385
		}
	}

	/**
Qiang Xue committed
386
	 * Finds the layout file that can be applied to the view.
Qiang Xue committed
387
	 *
Qiang Xue committed
388
	 * The applicable layout is resolved according to the following rules:
Qiang Xue committed
389
	 *
Qiang Xue committed
390 391 392 393 394 395
	 * - If [[layout]] is specified as a string, use it as the layout name and search for the layout file
	 *   under the layout path of the currently active module;
	 * - If [[layout]] is null and [[owner]] is a controller:
	 *      * If the controller's [[Controller::layout|layout]] is a string, use it as the layout name
	 *        and search for the layout file under the layout path of the parent module of the controller;
	 *      * If the controller's [[Controller::layout|layout]] is null, look through its ancestor modules
Qiang Xue committed
396 397
	 *        and find the first one whose [[Module::layout|layout]] is not null. Use the layout specified
	 *        by that module;
Qiang Xue committed
398
	 * - Returns false for all other cases.
Qiang Xue committed
399
	 *
Qiang Xue committed
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
	 * Like view names, a layout name can take several formats:
	 *
	 * - path alias (e.g. "@application/views/layouts/main");
	 * - absolute path (e.g. "/main"): the layout name starts with a slash. The actual layout file will be
	 *   looked for under the [[Application::layoutPath|layout path]] of the application;
	 * - relative path (e.g. "main"): the actual layout layout file will be looked for under the
	 *   [[Module::viewPath|view path]] of the context module determined by the above layout resolution process.
	 *
	 * If the layout name does not contain a file extension, it will default to `.php`.
	 *
	 * If [[enableTheme]] is true and there is an active application them, the method will also
	 * attempt to use a themed version of the layout file, when available.
	 *
	 * And if [[enableI18N]] is true, the method will attempt to use a translated version of the layout file,
	 * when available.
	 *
	 * @return string|boolean the layout file path, or false if layout is not needed.
	 * @throws InvalidConfigException if the layout file cannot be found
Qiang Xue committed
418 419 420
	 */
	public function findLayoutFile()
	{
Qiang Xue committed
421
		/** @var $module Module */
Qiang Xue committed
422 423 424 425 426 427 428
		if (is_string($this->layout)) {
			if (Yii::$application->controller) {
				$module = Yii::$application->controller->module;
			} else {
				$module = Yii::$application;
			}
			$view = $this->layout;
Qiang Xue committed
429
		} elseif ($this->owner instanceof Controller) {
Qiang Xue committed
430 431 432 433 434 435 436 437
			if (is_string($this->owner->layout)) {
				$module = $this->owner->module;
				$view = $this->owner->layout;
			} elseif ($this->owner->layout === null) {
				$module = $this->owner->module;
				while ($module !== null && $module->layout === null) {
					$module = $module->module;
				}
Qiang Xue committed
438 439
				if ($module !== null && is_string($module->layout)) {
					$view = $module->layout;
Qiang Xue committed
440 441
				}
			}
Qiang Xue committed
442 443 444
		}

		if (!isset($view)) {
Qiang Xue committed
445 446 447
			return false;
		}

Qiang Xue committed
448
		if (FileHelper::getExtension($view) === '') {
Qiang Xue committed
449 450 451
			$view .= '.php';
		}
		if (strncmp($view, '@', 1) === 0) {
Qiang Xue committed
452 453
			if (($file = Yii::getAlias($view)) === false) {
				throw new InvalidConfigException("Invalid path alias: $view");
Qiang Xue committed
454
			}
Qiang Xue committed
455
		} elseif (strncmp($view, '/', 1) === 0) {
Qiang Xue committed
456
			$file = Yii::$application->getLayoutPath() . DIRECTORY_SEPARATOR . $view;
Qiang Xue committed
457
		} else {
Qiang Xue committed
458
			$file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $view;
Qiang Xue committed
459
		}
Qiang Xue committed
460 461 462 463 464 465

		if (is_file($file)) {
			if ($this->enableTheme && ($theme = Yii::$application->getTheme()) !== null) {
				$file = $theme->apply($file);
			}
			return $this->enableI18N ? FileHelper::localize($file, $this->language, $this->sourceLanguage) : $file;
466
		} else {
Qiang Xue committed
467
			throw new InvalidConfigException("Layout file for layout '$view' does not exist: $file");
468
		}
Qiang Xue committed
469
	}
Qiang Xue committed
470
}