3 * Methods for displaying presentation data in the view.
7 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8 * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
10 * Licensed under The MIT License
11 * Redistributions of files must retain the above copyright notice.
13 * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
14 * @link http://cakephp.org CakePHP(tm) Project
16 * @subpackage cake.cake.libs.view
17 * @since CakePHP(tm) v 0.10.0.1076
18 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
24 App
::import('Core', 'ClassRegistry');
25 App
::import('View', 'Helper', false);
28 * View, the V in the MVC triad.
30 * Class holding methods for displaying presentation data.
33 * @subpackage cake.cake.libs.view
35 class View
extends Object {
38 * Path parts for creating links in views.
40 * @var string Base URL
46 * Stores the current URL (for links etc.)
48 * @var string Current URL
55 * @link http://manual.cakephp.org/chapter/plugins
61 * Name of the controller.
63 * @var string Name of controller
69 * Action to be performed.
71 * @var string Name of action
77 * Array of parameter data
79 * @var array Parameter data
81 var $params = array();
84 * Current passed params
88 var $passedArgs = array();
93 * @var array Parameter data
98 * An array of names of built-in helpers to include.
100 * @var mixed A single name as a string or a list of names as an array.
103 var $helpers = array('Html');
108 * @var string Path to View
110 var $viewPath = null;
113 * Variables for the view
118 var $viewVars = array();
121 * Name of layout to use with this View.
126 var $layout = 'default';
131 * @var string Path to Layout
133 var $layoutPath = null;
136 * Turns on or off Cake's conventional mode of rendering views. On by default.
141 var $autoRender = true;
144 * Turns on or off Cake's conventional mode of finding layout files. On by default.
149 var $autoLayout = true;
152 * File extension. Defaults to Cake's template ".ctp".
160 * Sub-directory for this view file.
176 * Used to define methods a controller that will be cached.
178 * @see Controller::$cacheAction
182 var $cacheAction = false;
185 * holds current errors for the model validation
190 var $validationErrors = array();
193 * True when the view has been rendered.
198 var $hasRendered = false;
201 * Array of loaded view helpers.
206 var $loaded = array();
209 * True if in scope of model-specific region
214 var $modelScope = false;
217 * Name of current model this view context is attached to
225 * Name of association model this view context is attached to
230 var $association = null;
233 * Name of current model field this view context is attached to
241 * Suffix of current field this view context is attached to
246 var $fieldSuffix = null;
249 * The current model ID this view context is attached to
257 * List of generated DOM UUIDs
262 var $uuids = array();
273 * List of variables to collect from the associated controller
278 var $__passedVars = array(
279 'viewVars', 'action', 'autoLayout', 'autoRender', 'ext', 'base', 'webroot',
280 'helpers', 'here', 'layout', 'name', 'layoutPath', 'viewPath',
281 'params', 'data', 'plugin', 'passedArgs', 'cacheAction'
285 * Scripts (and/or other <head /> tags) for the layout
290 var $__scripts = array();
293 * Holds an array of paths.
298 var $__paths = array();
303 * @param Controller $controller A controller object to pull View::__passedArgs from.
304 * @param boolean $register Should the View instance be registered in the ClassRegistry
307 function __construct(&$controller, $register = true) {
308 if (is_object($controller)) {
309 $count = count($this->__passedVars
);
310 for ($j = 0; $j < $count; $j++
) {
311 $var = $this->__passedVars
[$j];
312 $this->{$var} = $controller->{$var};
315 parent
::__construct();
318 ClassRegistry
::addObject('view', $this);
323 * Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
325 * This realizes the concept of Elements, (or "partial layouts")
326 * and the $params array is used to send data to be used in the
327 * Element. Elements can be cached through use of the cache key.
331 * - `cache` - enable caching for this element accepts boolean or strtotime compatible string.
332 * Can also be an array. If `cache` is an array,
333 * `time` is used to specify duration of cache.
334 * `key` can be used to create unique cache files.
335 * - `plugin` - Load an element from a specific plugin.
337 * @param string $name Name of template file in the/app/views/elements/ folder
338 * @param array $params Array of data to be made available to the for rendered
339 * view (i.e. the Element)
340 * @return string Rendered Element
343 function element($name, $params = array(), $loadHelpers = false) {
344 $file = $plugin = $key = null;
346 if (isset($params['plugin'])) {
347 $plugin = $params['plugin'];
350 if (isset($this->plugin
) && !$plugin) {
351 $plugin = $this->plugin
;
354 if (isset($params['cache'])) {
357 if (is_array($params['cache'])) {
358 $expires = $params['cache']['time'];
359 $key = Inflector
::slug($params['cache']['key']);
360 } elseif ($params['cache'] !== true) {
361 $expires = $params['cache'];
362 $key = implode('_', array_keys($params));
366 $cacheFile = 'element_' . $key . '_' . $plugin . Inflector
::slug($name);
367 $cache = cache('views' . DS
. $cacheFile, null, $expires);
369 if (is_string($cache)) {
374 $paths = $this->_paths($plugin);
375 $exts = $this->_getExtensions();
376 foreach ($exts as $ext) {
377 foreach ($paths as $path) {
378 if (file_exists($path . 'elements' . DS
. $name . $ext)) {
379 $file = $path . 'elements' . DS
. $name . $ext;
385 if (is_file($file)) {
386 $vars = array_merge($this->viewVars
, $params);
387 foreach ($this->loaded
as $name => $helper) {
388 if (!isset($vars[$name])) {
389 $vars[$name] =& $this->loaded
[$name];
392 $element = $this->_render($file, $vars, $loadHelpers);
393 if (isset($params['cache']) && isset($cacheFile) && isset($expires)) {
394 cache('views' . DS
. $cacheFile, $element, $expires);
398 $file = $paths[0] . 'elements' . DS
. $name . $this->ext
;
400 if (Configure
::read() > 0) {
401 return "Not Found: " . $file;
406 * Renders view for given action and layout. If $file is given, that is used
407 * for a view filename (e.g. customFunkyView.ctp).
409 * @param string $action Name of action to render for
410 * @param string $layout Layout to use
411 * @param string $file Custom filename for view
412 * @return string Rendered Element
415 function render($action = null, $layout = null, $file = null) {
416 if ($this->hasRendered
) {
425 if ($action !== false && $viewFileName = $this->_getViewFileName($action)) {
426 $out = $this->_render($viewFileName, $this->viewVars
);
429 if ($layout === null) {
430 $layout = $this->layout
;
433 if ($out !== false) {
434 if ($layout && $this->autoLayout
) {
435 $out = $this->renderLayout($out, $layout);
437 isset($this->loaded
['cache']) ||
438 Configure
::read('Cache.check') === true
442 $replace = array('<cake:nocache>', '</cake:nocache>');
443 $out = str_replace($replace, '', $out);
446 $this->hasRendered
= true;
448 $out = $this->_render($viewFileName, $this->viewVars
);
449 trigger_error(sprintf(__("Error in view %s, got: <blockquote>%s</blockquote>", true), $viewFileName, $out), E_USER_ERROR
);
455 * Renders a layout. Returns output from _render(). Returns false on error.
456 * Several variables are created for use in layout.
458 * - `title_for_layout` - A backwards compatible place holder, you should set this value if you want more control.
459 * - `content_for_layout` - contains rendered view file
460 * - `scripts_for_layout` - contains scripts added to header
462 * @param string $content_for_layout Content to render in a view, wrapped by the surrounding layout.
463 * @return mixed Rendered output, or false on error
466 function renderLayout($content_for_layout, $layout = null) {
467 $layoutFileName = $this->_getLayoutFileName($layout);
468 if (empty($layoutFileName)) {
469 return $this->output
;
472 $dataForLayout = array_merge($this->viewVars
, array(
473 'content_for_layout' => $content_for_layout,
474 'scripts_for_layout' => implode("\n\t", $this->__scripts
),
477 if (!isset($dataForLayout['title_for_layout'])) {
478 $dataForLayout['title_for_layout'] = Inflector
::humanize($this->viewPath
);
481 if (empty($this->loaded
) && !empty($this->helpers
)) {
484 $loadHelpers = false;
485 $dataForLayout = array_merge($dataForLayout, $this->loaded
);
488 $this->_triggerHelpers('beforeLayout');
489 $this->output
= $this->_render($layoutFileName, $dataForLayout, $loadHelpers, true);
491 if ($this->output
=== false) {
492 $this->output
= $this->_render($layoutFileName, $dataForLayout);
493 trigger_error(sprintf(__("Error in layout %s, got: <blockquote>%s</blockquote>", true), $layoutFileName, $this->output
), E_USER_ERROR
);
497 $this->_triggerHelpers('afterLayout');
499 return $this->output
;
503 * Fire a callback on all loaded Helpers. All helpers must implement this method,
504 * it is not checked before being called. You can add additional helper callbacks in AppHelper.
506 * @param string $callback name of callback fire.
510 function _triggerHelpers($callback) {
511 if (empty($this->loaded
)) {
514 $helpers = array_keys($this->loaded
);
515 foreach ($helpers as $helperName) {
516 $helper =& $this->loaded
[$helperName];
517 if (is_object($helper)) {
518 if (is_subclass_of($helper, 'Helper')) {
519 $helper->{$callback}();
526 * Render cached view. Works in concert with CacheHelper and Dispatcher to
527 * render cached view files.
529 * @param string $filename the cache file to include
530 * @param string $timeStart the page render start time
531 * @return boolean Success of rendering the cached file.
534 function renderCache($filename, $timeStart) {
538 if (Configure
::read() > 0 && $this->layout
!= 'xml') {
539 echo "<!-- Cached Render Time: " . round(getMicrotime() - $timeStart, 4) . "s -->";
541 $out = ob_get_clean();
543 if (preg_match('/^<!--cachetime:(\\d+)-->/', $out, $match)) {
544 if (time() >= $match['1']) {
549 if ($this->layout
=== 'xml') {
550 header('Content-type: text/xml');
552 $commentLength = strlen('<!--cachetime:' . $match['1'] . '-->');
553 echo substr($out, $commentLength);
560 * Returns a list of variables available in the current View context
562 * @return array Array of the set view variable names.
566 return array_keys($this->viewVars
);
570 * Returns the contents of the given View variable(s)
572 * @param string $var The view var you want the contents of.
573 * @return mixed The content of the named var if its set, otherwise null.
576 function getVar($var) {
577 if (!isset($this->viewVars
[$var])) {
580 return $this->viewVars
[$var];
585 * Adds a script block or other element to be inserted in $scripts_for_layout in
586 * the `<head />` of a document layout
588 * @param string $name Either the key name for the script, or the script content. Name can be used to
589 * update/replace a script element.
590 * @param string $content The content of the script being added, optional.
594 function addScript($name, $content = null) {
595 if (empty($content)) {
596 if (!in_array($name, array_values($this->__scripts
))) {
597 $this->__scripts
[] = $name;
600 $this->__scripts
[$name] = $content;
605 * Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.
607 * @param string $object Type of object, i.e. 'form' or 'link'
608 * @param string $url The object's target URL
612 function uuid($object, $url) {
614 $url = Router
::url($url);
615 $hash = $object . substr(md5($object . $url), 0, 10);
616 while (in_array($hash, $this->uuids
)) {
617 $hash = $object . substr(md5($object . $url . $c), 0, 10);
620 $this->uuids
[] = $hash;
625 * Returns the entity reference of the current context as an array of identity parts
627 * @return array An array containing the identity elements of an entity
631 $assoc = ($this->association
) ?
$this->association
: $this->model
;
632 if (!empty($this->entityPath
)) {
633 $path = explode('.', $this->entityPath
);
634 $count = count($path);
636 ($count == 1 && !empty($this->association
)) ||
637 ($count == 1 && $this->model
!= $this->entityPath
) ||
638 ($count == 1 && empty($this->association
) && !empty($this->field
)) ||
639 ($count == 2 && !empty($this->fieldSuffix
)) ||
640 is_numeric($path[0]) && !empty($assoc)
642 array_unshift($path, $assoc);
644 return Set
::filter($path);
646 return array_values(Set
::filter(
647 array($assoc, $this->modelId
, $this->field
, $this->fieldSuffix
)
652 * Allows a template or element to set a variable that will be available in
653 * a layout or other element. Analagous to Controller::set.
655 * @param mixed $one A string or an array of data.
656 * @param mixed $two Value in case $one is a string (which then works as the key).
657 * Unused if $one is an associative array, otherwise serves as the values to $one's keys.
661 function set($one, $two = null) {
663 if (is_array($one)) {
664 if (is_array($two)) {
665 $data = array_combine($one, $two);
670 $data = array($one => $two);
675 $this->viewVars
= $data +
$this->viewVars
;
679 * Displays an error page to the user. Uses layouts/error.ctp to render the page.
681 * @param integer $code HTTP Error code (for instance: 404)
682 * @param string $name Name of the error (for instance: Not Found)
683 * @param string $message Error message as a web page
686 function error($code, $name, $message) {
687 header ("HTTP/1.1 {$code} {$name}");
688 print ($this->_render(
689 $this->_getLayoutFileName('error'),
690 array('code' => $code, 'name' => $name, 'message' => $message)
695 * Renders and returns output for given view filename with its
698 * @param string $___viewFn Filename of the view
699 * @param array $___dataForView Data to include in rendered view
700 * @param boolean $loadHelpers Boolean to indicate that helpers should be loaded.
701 * @param boolean $cached Whether or not to trigger the creation of a cache file.
702 * @return string Rendered output
705 function _render($___viewFn, $___dataForView, $loadHelpers = true, $cached = false) {
706 $loadedHelpers = array();
708 if ($this->helpers
!= false && $loadHelpers === true) {
709 $loadedHelpers = $this->_loadHelpers($loadedHelpers, $this->helpers
);
710 $helpers = array_keys($loadedHelpers);
711 $helperNames = array_map(array('Inflector', 'variable'), $helpers);
713 for ($i = count($helpers) - 1; $i >= 0; $i--) {
714 $name = $helperNames[$i];
715 $helper =& $loadedHelpers[$helpers[$i]];
717 if (!isset($___dataForView[$name])) {
720 $this->loaded
[$helperNames[$i]] =& $helper;
721 $this->{$helpers[$i]} =& $helper;
723 $this->_triggerHelpers('beforeRender');
724 unset($name, $loadedHelpers, $helpers, $i, $helperNames, $helper);
727 extract($___dataForView, EXTR_SKIP
);
730 if (Configure
::read() > 0) {
731 include ($___viewFn);
733 @include
($___viewFn);
736 if ($loadHelpers === true) {
737 $this->_triggerHelpers('afterRender');
740 $out = ob_get_clean();
742 isset($this->loaded
['cache']) &&
743 (($this->cacheAction
!= false)) && (Configure
::read('Cache.check') === true)
747 if (is_a($this->loaded
['cache'], 'CacheHelper')) {
748 $cache =& $this->loaded
['cache'];
749 $cache->base
= $this->base
;
750 $cache->here
= $this->here
;
751 $cache->helpers
= $this->helpers
;
752 $cache->action
= $this->action
;
753 $cache->controllerName
= $this->name
;
754 $cache->layout
= $this->layout
;
755 $cache->cacheAction
= $this->cacheAction
;
756 $cache->viewVars
= $this->viewVars
;
757 $cache->cache($___viewFn, $out, $cached);
764 * Loads helpers, with their dependencies.
766 * @param array $loaded List of helpers that are already loaded.
767 * @param array $helpers List of helpers to load.
768 * @param string $parent holds name of helper, if loaded helper has helpers
769 * @return array Array containing the loaded helpers.
772 function &_loadHelpers(&$loaded, $helpers, $parent = null) {
773 foreach ($helpers as $i => $helper) {
780 list($plugin, $helper) = pluginSplit($helper, true, $this->plugin
);
781 $helperCn = $helper . 'Helper';
783 if (!isset($loaded[$helper])) {
784 if (!class_exists($helperCn)) {
786 if (!is_null($plugin)) {
787 $isLoaded = App
::import('Helper', $plugin . $helper);
790 if (!App
::import('Helper', $helper)) {
791 $this->cakeError('missingHelperFile', array(array(
793 'file' => Inflector
::underscore($helper) . '.php',
794 'base' => $this->base
799 if (!class_exists($helperCn)) {
800 $this->cakeError('missingHelperClass', array(array(
802 'file' => Inflector
::underscore($helper) . '.php',
803 'base' => $this->base
808 $loaded[$helper] =& new $helperCn($options);
809 $vars = array('base', 'webroot', 'here', 'params', 'action', 'data', 'theme', 'plugin');
812 for ($j = 0; $j < $c; $j++
) {
813 $loaded[$helper]->{$vars[$j]} = $this->{$vars[$j]};
816 if (!empty($this->validationErrors
)) {
817 $loaded[$helper]->validationErrors
= $this->validationErrors
;
819 if (is_array($loaded[$helper]->helpers
) && !empty($loaded[$helper]->helpers
)) {
820 $loaded =& $this->_loadHelpers($loaded, $loaded[$helper]->helpers
, $helper);
823 if (isset($loaded[$parent])) {
824 $loaded[$parent]->{$helper} =& $loaded[$helper];
831 * Returns filename of given action's template file (.ctp) as a string.
832 * CamelCased action names will be under_scored! This means that you can have
833 * LongActionNames that refer to long_action_names.ctp views.
835 * @param string $name Controller action to find template filename for
836 * @return string Template filename
839 function _getViewFileName($name = null) {
842 if (!is_null($this->subDir
)) {
843 $subDir = $this->subDir
. DS
;
846 if ($name === null) {
847 $name = $this->action
;
849 $name = str_replace('/', DS
, $name);
851 if (strpos($name, DS
) === false && $name[0] !== '.') {
852 $name = $this->viewPath
. DS
. $subDir . Inflector
::underscore($name);
853 } elseif (strpos($name, DS
) !== false) {
854 if ($name{0} === DS ||
$name{1} === ':') {
855 if (is_file($name)) {
858 $name = trim($name, DS
);
859 } else if ($name[0] === '.') {
860 $name = substr($name, 3);
862 $name = $this->viewPath
. DS
. $subDir . $name;
865 $paths = $this->_paths(Inflector
::underscore($this->plugin
));
867 $exts = $this->_getExtensions();
868 foreach ($exts as $ext) {
869 foreach ($paths as $path) {
870 if (file_exists($path . $name . $ext)) {
871 return $path . $name . $ext;
875 $defaultPath = $paths[0];
878 $pluginPaths = App
::path('plugins');
879 foreach ($paths as $path) {
880 if (strpos($path, $pluginPaths[0]) === 0) {
881 $defaultPath = $path;
886 return $this->_missingView($defaultPath . $name . $this->ext
, 'missingView');
890 * Returns layout filename for this template as a string.
892 * @param string $name The name of the layout to find.
893 * @return string Filename for layout file (.ctp).
896 function _getLayoutFileName($name = null) {
897 if ($name === null) {
898 $name = $this->layout
;
902 if (!is_null($this->layoutPath
)) {
903 $subDir = $this->layoutPath
. DS
;
905 $paths = $this->_paths(Inflector
::underscore($this->plugin
));
906 $file = 'layouts' . DS
. $subDir . $name;
908 $exts = $this->_getExtensions();
909 foreach ($exts as $ext) {
910 foreach ($paths as $path) {
911 if (file_exists($path . $file . $ext)) {
912 return $path . $file . $ext;
916 return $this->_missingView($paths[0] . $file . $this->ext
, 'missingLayout');
921 * Get the extensions that view files can use.
923 * @return array Array of extensions view files use.
926 function _getExtensions() {
927 $exts = array($this->ext
);
928 if ($this->ext
!== '.ctp') {
929 array_push($exts, '.ctp');
935 * Return a misssing view error message
937 * @param string $viewFileName the filename that should exist
941 function _missingView($file, $error = 'missingView') {
942 if ($error === 'missingView') {
943 $this->cakeError('missingView', array(
944 'className' => $this->name
,
945 'action' => $this->action
,
947 'base' => $this->base
950 } elseif ($error === 'missingLayout') {
951 $this->cakeError('missingLayout', array(
952 'layout' => $this->layout
,
954 'base' => $this->base
961 * Return all possible paths to find view files in order
963 * @param string $plugin Optional plugin name to scan for view files.
964 * @param boolean $cached Set to true to force a refresh of view paths.
965 * @return array paths
968 function _paths($plugin = null, $cached = true) {
969 if ($plugin === null && $cached === true && !empty($this->__paths
)) {
970 return $this->__paths
;
973 $viewPaths = App
::path('views');
974 $corePaths = array_flip(App
::core('views'));
976 if (!empty($plugin)) {
977 $count = count($viewPaths);
978 for ($i = 0; $i < $count; $i++
) {
979 if (!isset($corePaths[$viewPaths[$i]])) {
980 $paths[] = $viewPaths[$i] . 'plugins' . DS
. $plugin . DS
;
983 $paths[] = App
::pluginPath($plugin) . 'views' . DS
;
985 $this->__paths
= array_merge($paths, $viewPaths);
986 return $this->__paths
;