W3cubDocs

/CakePHP 3.8

Class View

View, the V in the MVC triad. View interacts with Helpers and view variables passed in from the controller to render the results of the controller action. Often this is HTML, but can also take the form of JSON, XML, PDF's or streaming files.

CakePHP uses a two-step-view pattern. This means that the template content is rendered first, and then inserted into the selected layout. This also means you can pass data from the template to the layout using $this->set()

View class supports using plugins as themes. You can set

public function beforeRender(\Cake\Event\Event $event)
{
     $this->viewBuilder()->setTheme('SuperHot');
}

in your Controller to use plugin SuperHot as a theme. Eg. If current action is PostsController::index() then View class will look for template file plugins/SuperHot/Template/Posts/index.ctp. If a theme template is not found for the current action the default app template file is used.

Cake\View\View implements Cake\Event\EventDispatcherInterface uses Cake\View\CellTrait , Cake\Event\EventDispatcherTrait , Cake\Log\LogTrait , Cake\Routing\RequestActionTrait , Cake\View\ViewVarsTrait

Direct Subclasses

Indirect Subclasses

Namespace: Cake\View
Location: View/View.php

Constants summary

  • string

    NAME_ELEMENT
    'Element'
  • string

    NAME_TEMPLATE
    'Template'
  • string

    TYPE_ELEMENT
    'element'
  • string

    TYPE_LAYOUT
    'layout'
  • string

    TYPE_TEMPLATE
    'view'
  • string

    TYPE_VIEW
    'view'

Properties summary

  • $Blocks protected
    ViewBlock instance.
  • $_current protected
    string
    The currently rendering view file. Used for resolving parent files.
  • $_currentType protected
    string

    Currently rendering an element. Used for finding parent fragments for elements.

  • $_ext protected
    string
    File extension. Defaults to CakePHP's template ".ctp".
  • $_helpers protected
    Helpers collection
  • $_parents protected
    array
    The names of views and their parents used with View::extend();
  • $_passedVars protected
    array
    List of variables to collect from the associated controller.
  • $_paths protected
    array
    Holds an array of paths.
  • $_pathsForPlugin protected
    array
    Holds an array of plugin paths.
  • $_stack protected
    array
    Content stack, used for nested templates that all use View::extend();
  • $_viewBlockClass protected
    string
    ViewBlock class.
  • $autoLayout protected
    boolean

    Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.

  • $elementCache protected
    string

    The Cache configuration View will use to store cached elements. Changing this will change the default configuration elements are stored under. You can also choose a cache config per element.

  • $hasRendered public
    boolean
    True when the view has been rendered.
  • $helpers protected
    array
    An array of names of built-in helpers to include.
  • $layout protected
    string

    The name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.

  • $layoutPath protected
    string
    The name of the layouts subfolder containing layouts for this View.
  • $name protected
    string
    Name of the controller that created the View if any.
  • $passedArgs public
    array
    Current passed params. Passed to View from the creating Controller for convenience.
  • $plugin protected
    string|null
    The name of the plugin.
  • $request protected

    An instance of a \Cake\Http\ServerRequest object that contains information about the current request. This object contains all the information about a request and several methods for reading additional information about the request.

  • $response protected
    Reference to the Response object
  • $subDir protected
    string

    Sub-directory for this template file. This is often used for extension based routing. Eg. With an xml extension, $subDir would be xml/

  • $template protected
    string

    The name of the template file to render. The name specified is the filename in /src/Template/ without the .ctp extension.

  • $templatePath protected
    string
    The name of the subfolder containing templates for this View.
  • $theme protected
    string|null
    The view theme to use.
  • $uuids public
    array
    List of generated DOM UUIDs.

Magic properties summary

Inherited Magic Properties

Inherited Properties

Method Summary

  • __construct() public
    Constructor
  • __get() public
    Magic accessor for helpers.
  • __set() public
    Magic setter for deprecated properties.
  • _checkFilePath() protected
    Check that a view file path does not go outside of the defined template paths.
  • _elementCache() protected
    Generate the cache configuration options for an element.
  • _evaluate() protected
    Sandbox method to evaluate a template / view script in.
  • Finds an element filename, returns false on failure.
  • Returns layout filename for this template as a string.
  • _getSubPaths() protected

    Find all sub templates path, based on $basePath If a prefix is defined in the current request, this method will prepend the prefixed template path to the $basePath, cascading up in case the prefix is nested. This is essentially used to find prefixed template paths for elements and layouts.

  • _getViewFileName() protected

    Returns filename of given action's template file (.ctp) as a string. CamelCased action names will be under_scored by default. This means that you can have LongActionNames that refer to long_action_names.ctp views. You can change the inflection rule by overriding _inflectViewFileName.

  • Change the name of a view template file into underscored format.
  • _paths() protected
    Return all possible paths to find view files in order
  • _render() protected

    Renders and returns output for given template filename with its array of data. Handles parent/extended templates.

  • _renderElement() protected

    Renders an element and fires the before and afterRender callbacks for it and writes to the cache if a cache is used

  • append() public
    Append to an existing or new block.
  • assign() public

    Set the content for a block. This will overwrite any existing content.

  • autoLayout() public deprecated

    Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.

  • blocks() public
    Get the names of all the existing blocks.
  • cache() public
    Create a cached block of view logic.
  • Turns off CakePHP's conventional mode of applying layout files.
  • element() public
    Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
  • Checks if an element exists
  • Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered views.

  • end() public
    End a capturing block. The compliment to View::start()
  • exists() public
    Check if a block exists
  • extend() public

    Provides template or element extension/inheritance. Views can extends a parent view and populate blocks in the parent template.

  • fetch() public

    Fetch the content for a block. If a block is empty or undefined '' will be returned.

  • get() public
    Returns the contents of the given View variable.
  • Retrieve the current view type
  • getLayout() public

    Get the name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.

  • Get path for layout files.
  • getName() public
    Returns the View's controller name.
  • getPlugin() public
    Returns the plugin name.
  • getRequest() public
    Gets the request instance.
  • getResponse() public
    Gets the response instance.
  • getSubDir() public
    Get sub-directory for this template files.
  • getTemplate() public

    Get the name of the template file to render. The name specified is the filename in /src/Template/ without the .ctp extension.

  • Get path for templates files.
  • getTheme() public
    Get the current view theme.
  • getVars() public
    Returns a list of variables available in the current View context
  • helpers() public
    Get the helper registry in use by this View class.
  • initialize() public
    Initialization hook method.
  • Returns if CakePHP's conventional mode of applying layout files is enabled. Disabled means that layouts will not be automatically applied to rendered views.

  • layout() public deprecated

    Get/set the name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.

  • layoutPath() public deprecated
    Get/set path for layout files.
  • loadHelper() public
    Loads a helper. Delegates to the HelperRegistry::load() to load the helper
  • loadHelpers() public
    Interact with the HelperRegistry to load all the helpers.
  • pluginSplit() public

    Splits a dot syntax plugin name into its plugin and filename. If $name does not have a dot, then index 0 will be null. It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot

  • prepend() public
    Prepend to an existing or new block.
  • render() public
    Renders view for given template file and layout.
  • Renders a layout. Returns output from _render(). Returns false on error. Several variables are created for use in layout.

  • reset() public

    Reset the content for a block. This will overwrite any existing content.

  • Set The cache configuration View will use to store cached elements
  • setLayout() public

    Set the name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.

  • Set path for layout files.
  • setPlugin() public
    Sets the plugin name.
  • setRequest() public

    Sets the request objects and configures a number of controller properties based on the contents of the request. The properties that get set are:

  • setResponse() public
    Sets the response instance.
  • setSubDir() public
    Set sub-directory for this template files.
  • setTemplate() public

    Set the name of the template file to render. The name specified is the filename in /src/Template/ without the .ctp extension.

  • Set path for templates files.
  • setTheme() public
    Set the view theme to use.
  • start() public
    Start capturing output for a 'block'
  • template() public deprecated

    Get/set the name of the template file to render. The name specified is the filename in /src/Template/ without the .ctp extension.

  • templatePath() public deprecated
    Get/set path for templates files.
  • theme() public deprecated
    The view theme to use.
  • uuid() public deprecated
    Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.

Method Detail

__construct()source public

__construct( Cake\Http\ServerRequest $request = null , Cake\Http\Response $response = null , Cake\Event\EventManager $eventManager = null , array $viewOptions = [] )

Constructor

Parameters

Cake\Http\ServerRequest $request optional null
Request instance.
Cake\Http\Response $response optional null
Response instance.
Cake\Event\EventManager $eventManager optional null
Event manager instance.
array $viewOptions optional []

View options. See View::$_passedVars for list of options which get set as class properties.

__get()source public

__get( string $name )

Magic accessor for helpers.

Parameters

string $name
Name of the attribute to get.

Returns

mixed

__set()source public

__set( string $name , mixed $value )

Magic setter for deprecated properties.

Parameters

string $name
Name to property.
mixed $value
Value for property.

_checkFilePath()source protected

_checkFilePath( string $file , string $path )

Check that a view file path does not go outside of the defined template paths.

Only paths that contain .. will be checked, as they are the ones most likely to have the ability to resolve to files outside of the template paths.

Parameters

string $file
The path to the template file.
string $path
Base path that $file should be inside of.

Returns

string
The file path

Throws

InvalidArgumentException

_elementCache()source protected

_elementCache( string $name , array $data , array $options )

Generate the cache configuration options for an element.

Parameters

string $name
Element name
array $data
Data
array $options
Element options

Returns

array
Element Cache configuration.

_evaluate()source protected

_evaluate( string $viewFile , array $dataForView )

Sandbox method to evaluate a template / view script in.

Parameters

string $viewFile
Filename of the view
array $dataForView
Data to include in rendered view.

Returns

string
Rendered output

_getElementFileName()source protected

_getElementFileName( string $name , boolean $pluginCheck = true )

Finds an element filename, returns false on failure.

Parameters

string $name
The name of the element to find.
boolean $pluginCheck optional true
  • if false will ignore the request's plugin if parsed plugin is not loaded

Returns

string|false
Either a string to the element filename or false when one can't be found.

_getLayoutFileName()source protected

_getLayoutFileName( string|null $name = null )

Returns layout filename for this template as a string.

Parameters

string|null $name optional null
The name of the layout to find.

Returns

string
Filename for layout file (.ctp).

Throws

Cake\View\Exception\MissingLayoutException
when a layout cannot be located

_getSubPaths()source protected

_getSubPaths( string $basePath )

Find all sub templates path, based on $basePath If a prefix is defined in the current request, this method will prepend the prefixed template path to the $basePath, cascading up in case the prefix is nested. This is essentially used to find prefixed template paths for elements and layouts.

Parameters

string $basePath
Base path on which to get the prefixed one.

Returns

array
Array with all the templates paths.

_getViewFileName()source protected

_getViewFileName( string|null $name = null )

Returns filename of given action's template file (.ctp) as a string. CamelCased action names will be under_scored by default. This means that you can have LongActionNames that refer to long_action_names.ctp views. You can change the inflection rule by overriding _inflectViewFileName.

Parameters

string|null $name optional null
Controller action to find template filename for

Returns

string
Template filename

Throws

Cake\View\Exception\MissingTemplateException
when a view file could not be found.

_inflectViewFileName()source protected

_inflectViewFileName( string $name )

Change the name of a view template file into underscored format.

Parameters

string $name
Name of file which should be inflected.

Returns

string
File name after conversion

_paths()source protected

_paths( string|null $plugin = null , boolean $cached = true )

Return all possible paths to find view files in order

Parameters

string|null $plugin optional null
Optional plugin name to scan for view files.
boolean $cached optional true
Set to false to force a refresh of view paths. Default true.

Returns

array
paths

_render()source protected

_render( string $viewFile , array $data = [] )

Renders and returns output for given template filename with its array of data. Handles parent/extended templates.

Parameters

string $viewFile
Filename of the view
array $data optional []

Data to include in rendered view. If empty the current View::$viewVars will be used.

Returns

string
Rendered output

Throws

LogicException
When a block is left open.

Triggers

View.beforeRenderFile $this, [$viewFile]
View.afterRenderFile $this, [$viewFile, $content]

_renderElement()source protected

_renderElement( string $file , array $data , array $options )

Renders an element and fires the before and afterRender callbacks for it and writes to the cache if a cache is used

Parameters

string $file
Element file path
array $data
Data to render
array $options
Element options

Returns

string

Triggers

View.beforeRender $this, [$file]
View.afterRender $this, [$file, $element]

append()source public

append( string $name , mixed $value = null )

Append to an existing or new block.

Appending to a new block will create the block.

Parameters

string $name
Name of the block
mixed $value optional null

The content for the block. Value will be type cast to string.

Returns


$this

See

\Cake\View\ViewBlock::concat()

assign()source public

assign( string $name , mixed $value )

Set the content for a block. This will overwrite any existing content.

Parameters

string $name
Name of the block
mixed $value

The content for the block. Value will be type cast to string.

Returns


$this

See

\Cake\View\ViewBlock::set()

autoLayout()source public deprecated

autoLayout( boolean|null $autoLayout = null )

Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.

Deprecated

3.5.0 Use isAutoLayoutEnabled()/enableAutoLayout() instead.

Parameters

boolean|null $autoLayout optional null
Boolean to turn on/off. If null returns current value.

Returns

boolean|null

blocks()source public

blocks( )

Get the names of all the existing blocks.

Returns

array
An array containing the blocks.

See

\Cake\View\ViewBlock::keys()

cache()source public

cache( callable $block , array $options = [] )

Create a cached block of view logic.

This allows you to cache a block of view output into the cache defined in elementCache.

This method will attempt to read the cache first. If the cache is empty, the $block will be run and the output stored.

Parameters

callable $block
The block of code that you want to cache the output of.
array $options optional []
The options defining the cache key etc.

Returns

string
The rendered content.

Throws

RuntimeException
When $options is lacking a 'key' option.

disableAutoLayout()source public

disableAutoLayout( )

Turns off CakePHP's conventional mode of applying layout files.

Layouts will not be automatically applied to rendered views.

Returns


$this

element()source public

element( string $name , array $data = [] , array $options = [] )

Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.

This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send data to be used in the element. Elements can be cached improving performance by using the cache option.

Parameters

string $name

Name of template file in the /src/Template/Element/ folder, or MyPlugin.template to use the template element from MyPlugin. If the element is not found in the plugin, the normal view path cascade will be searched.

array $data optional []
Array of data to be made available to the rendered view (i.e. the Element)
array $options optional []

Array of options. Possible keys are: - cache - Can either be true, to enable caching using the config in View::$elementCache. Or an array If an array, the following keys can be used: - config - Used to store the cached element in a custom cache configuration. - key - Used to define the key used in the Cache::write(). It will be prefixed with element_ - callbacks - Set to true to fire beforeRender and afterRender helper callbacks for this element. Defaults to false. - ignoreMissing - Used to allow missing elements. Set to true to not throw exceptions. - plugin - setting to false will force to use the application's element from plugin templates, when the plugin has element with same name. Defaults to true

Returns

string
Rendered Element

Throws

Cake\View\Exception\MissingElementException

When an element is missing and ignoreMissing is false.


elementExists()source public

elementExists( string $name )

Checks if an element exists

Parameters

string $name

Name of template file in the /src/Template/Element/ folder, or MyPlugin.template to check the template element from MyPlugin. If the element is not found in the plugin, the normal view path cascade will be searched.

Returns

boolean
Success

enableAutoLayout()source public

enableAutoLayout( boolean $enable = true )

Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered views.

Parameters

boolean $enable optional true
Boolean to turn on/off.

Returns


$this

end()source public

end( )

End a capturing block. The compliment to View::start()

Returns


$this

See

\Cake\View\ViewBlock::end()

exists()source public

exists( string $name )

Check if a block exists

Parameters

string $name
Name of the block

Returns

boolean

extend()source public

extend( string $name )

Provides template or element extension/inheritance. Views can extends a parent view and populate blocks in the parent template.

Parameters

string $name
The template or element to 'extend' the current one with.

Returns


$this

Throws

LogicException
when you extend a template with itself or make extend loops.
LogicException
when you extend an element which doesn't exist

fetch()source public

fetch( string $name , string $default = '' )

Fetch the content for a block. If a block is empty or undefined '' will be returned.

Parameters

string $name
Name of the block
string $default optional ''
Default text

Returns

string
The block content or $default if the block does not exist.

See

\Cake\View\ViewBlock::get()

get()source public

get( string $var , mixed $default = null )

Returns the contents of the given View variable.

Parameters

string $var
The view var you want the contents of.
mixed $default optional null
The default/fallback content of $var.

Returns

mixed
The content of the named var if its set, otherwise $default.

getCurrentType()source public

getCurrentType( )

Retrieve the current view type

Returns

string

getLayout()source public

getLayout( )

Get the name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.

Returns

string

getLayoutPath()source public

getLayoutPath( )

Get path for layout files.

Returns

string

getName()source public

getName( )

Returns the View's controller name.

Returns

string|null

Since

3.7.7

getPlugin()source public

getPlugin( )

Returns the plugin name.

Returns

string|null

Since

3.7.0

getRequest()source public

getRequest( )

Gets the request instance.

Returns

Cake\Http\ServerRequest

Since

3.7.0

getResponse()source public

getResponse( )

Gets the response instance.

Returns

Cake\Http\Response

Since

3.7.0

getSubDir()source public

getSubDir( )

Get sub-directory for this template files.

Returns

string

See

\Cake\View\View::$subDir

Since

3.7.0

getTemplate()source public

getTemplate( )

Get the name of the template file to render. The name specified is the filename in /src/Template/ without the .ctp extension.

Returns

string

getTemplatePath()source public

getTemplatePath( )

Get path for templates files.

Returns

string

getTheme()source public

getTheme( )

Get the current view theme.

Returns

string|null

getVars()source public

getVars( )

Returns a list of variables available in the current View context

Returns

string[]
Array of the set view variable names.

helpers()source public

helpers( )

Get the helper registry in use by this View class.

Returns

Cake\View\HelperRegistry

initialize()source public

initialize( )

Initialization hook method.

Properties like $helpers etc. cannot be initialized statically in your custom view class as they are overwritten by values from controller in constructor. So this method allows you to manipulate them as required after view instance is constructed.

isAutoLayoutEnabled()source public

isAutoLayoutEnabled( )

Returns if CakePHP's conventional mode of applying layout files is enabled. Disabled means that layouts will not be automatically applied to rendered views.

Returns

boolean

layout()source public deprecated

layout( string|null $name = null )

Get/set the name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.

Deprecated

3.5.0 Use getLayout()/setLayout() instead.

Parameters

string|null $name optional null
Layout file name to set. If null returns current name.

Returns

string|null

layoutPath()source public deprecated

layoutPath( string|null $path = null )

Get/set path for layout files.

Deprecated

3.5.0 Use getLayoutPath()/setLayoutPath() instead.

Parameters

string|null $path optional null
Path for layout files. If null returns current path.

Returns

string|null

loadHelper()source public

loadHelper( string $name , array $config = [] )

Loads a helper. Delegates to the HelperRegistry::load() to load the helper

Parameters

string $name
Name of the helper to load.
array $config optional []
Settings for the helper

Returns

Cake\View\Helper
a constructed helper object.

See

\Cake\View\HelperRegistry::load()

loadHelpers()source public

loadHelpers( )

Interact with the HelperRegistry to load all the helpers.

Returns


$this

pluginSplit()source public

pluginSplit( string $name , boolean $fallback = true )

Splits a dot syntax plugin name into its plugin and filename. If $name does not have a dot, then index 0 will be null. It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot

Parameters

string $name
The name you want to plugin split.
boolean $fallback optional true
If true uses the plugin set in the current Request when parsed plugin is not loaded

Returns

array
Array with 2 indexes. 0 => plugin name, 1 => filename

prepend()source public

prepend( string $name , mixed $value )

Prepend to an existing or new block.

Prepending to a new block will create the block.

Parameters

string $name
Name of the block
mixed $value

The content for the block. Value will be type cast to string.

Returns


$this

See

\Cake\View\ViewBlock::concat()

render()source public

render( string|false|null $view = null , string|null $layout = null )

Renders view for given template file and layout.

Render triggers helper callbacks, which are fired before and after the template are rendered, as well as before and after the layout. The helper callbacks are called:

  • beforeRender
  • afterRender
  • beforeLayout
  • afterLayout

If View::$autoRender is false and no $layout is provided, the template will be returned bare.

Template and layout names can point to plugin templates/layouts. Using the Plugin.template syntax a plugin template/layout can be used instead of the app ones. If the chosen plugin is not found the template will be located along the regular view path cascade.

Parameters

string|false|null $view optional null
Name of view file to use
string|null $layout optional null
Layout to use.

Returns

string|null
Rendered content or null if content already rendered and returned earlier.

Throws

Cake\Core\Exception\Exception
If there is an error in the view.

Triggers

View.beforeRender $this, [$viewFileName]
View.afterRender $this, [$viewFileName]

renderLayout()source public

renderLayout( string $content , string|null $layout = null )

Renders a layout. Returns output from _render(). Returns false on error. Several variables are created for use in layout.

Parameters

string $content
Content to render in a template, wrapped by the surrounding layout.
string|null $layout optional null
Layout name

Returns

mixed
Rendered output, or false on error

Throws

Cake\Core\Exception\Exception
if there is an error in the view.

Triggers

View.beforeLayout $this, [$layoutFileName]
View.afterLayout $this, [$layoutFileName]

reset()source public

reset( string $name )

Reset the content for a block. This will overwrite any existing content.

Parameters

string $name
Name of the block

Returns


$this

See

\Cake\View\ViewBlock::set()

setElementCache()source public

setElementCache( string $elementCache )

Set The cache configuration View will use to store cached elements

Parameters

string $elementCache
Cache config name.

Returns


$this

See

\Cake\View\View::$elementCache

Since

3.7.0

setLayout()source public

setLayout( string $name )

Set the name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.

Parameters

string $name
Layout file name to set.

Returns


$this

setLayoutPath()source public

setLayoutPath( string $path )

Set path for layout files.

Parameters

string $path
Path for layout files.

Returns


$this

setPlugin()source public

setPlugin( string $name )

Sets the plugin name.

Parameters

string $name
Plugin name.

Returns


$this

Since

3.7.0

setRequest()source public

setRequest( Cake\Http\ServerRequest $request )

Sets the request objects and configures a number of controller properties based on the contents of the request. The properties that get set are:

  • $this->request - To the $request parameter
  • $this->plugin - To the value returned by $request->getParam('plugin')
  • $this->passedArgs - Same as $request->params['pass]

Parameters

Cake\Http\ServerRequest $request
Request instance.

Returns


$this

Since

3.7.0

setResponse()source public

setResponse( Cake\Http\Response $response )

Sets the response instance.

Parameters

Cake\Http\Response $response
Response instance.

Returns


$this

Since

3.7.0

setSubDir()source public

setSubDir( string $subDir )

Set sub-directory for this template files.

Parameters

string $subDir
Sub-directory name.

Returns


$this

See

\Cake\View\View::$subDir

Since

3.7.0

setTemplate()source public

setTemplate( string $name )

Set the name of the template file to render. The name specified is the filename in /src/Template/ without the .ctp extension.

Parameters

string $name
Template file name to set.

Returns


$this

setTemplatePath()source public

setTemplatePath( string $path )

Set path for templates files.

Parameters

string $path
Path for template files.

Returns


$this

setTheme()source public

setTheme( string|null $theme )

Set the view theme to use.

Parameters

string|null $theme
Theme name.

Returns


$this

start()source public

start( string $name )

Start capturing output for a 'block'

You can use start on a block multiple times to append or prepend content in a capture mode.

// Append content to an existing block.
$this->start('content');
echo $this->fetch('content');
echo 'Some new content';
$this->end();

// Prepend content to an existing block
$this->start('content');
echo 'Some new content';
echo $this->fetch('content');
$this->end();

Parameters

string $name
The name of the block to capture for.

Returns


$this

See

\Cake\View\ViewBlock::start()

template()source public deprecated

template( string|null $name = null )

Get/set the name of the template file to render. The name specified is the filename in /src/Template/ without the .ctp extension.

Deprecated

3.5.0 Use getTemplate()/setTemplate() instead.

Parameters

string|null $name optional null
Template file name to set. If null returns current name.

Returns

string|null

templatePath()source public deprecated

templatePath( string|null $path = null )

Get/set path for templates files.

Deprecated

3.5.0 Use getTemplatePath()/setTemplatePath() instead.

Parameters

string|null $path optional null
Path for template files. If null returns current path.

Returns

string|null

theme()source public deprecated

theme( string|null $theme = null )

The view theme to use.

Deprecated

3.5.0 Use getTheme()/setTheme() instead.

Parameters

string|null $theme optional null
Theme name. If null returns current theme.

Returns

string|null

uuid()source public deprecated

uuid( string $object , string $url )

Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.

Deprecated

3.7.0 This method is deprecated and will be removed in 4.0.0.

Parameters

string $object
Type of object, i.e. 'form' or 'link'
string $url
The object's target URL

Returns

string

Methods used from Cake\View\CellTrait

_createCell()source protected

_createCell( string $className , string $action , string $plugin , array $options )

Create and configure the cell instance.

Parameters

string $className
The cell classname.
string $action
The action name.
string $plugin
The plugin name.
array $options
The constructor options for the cell.

Returns

Cake\View\Cell

cell()source protected

cell( string $cell , array $data = [] , array $options = [] )

Renders the given cell.

Example:

// Taxonomy\View\Cell\TagCloudCell::smallList()
$cell = $this->cell('Taxonomy.TagCloud::smallList', ['limit' => 10]);

// App\View\Cell\TagCloudCell::smallList()
$cell = $this->cell('TagCloud::smallList', ['limit' => 10]);

The display action will be used by default when no action is provided:

// Taxonomy\View\Cell\TagCloudCell::display()
$cell = $this->cell('Taxonomy.TagCloud');

Cells are not rendered until they are echoed.

Parameters

string $cell

You must indicate cell name, and optionally a cell action. e.g.: TagCloud::smallList will invoke View\Cell\TagCloudCell::smallList(), display action will be invoked by default when none is provided.

array $data optional []

Additional arguments for cell method. e.g.: cell('TagCloud::smallList', ['a1' => 'v1', 'a2' => 'v2']) maps to View\Cell\TagCloud::smallList(v1, v2)

array $options optional []
Options for Cell's constructor

Returns

Cake\View\Cell
The cell instance

Throws

Cake\View\Exception\MissingCellException
If Cell class was not found.
BadMethodCallException
If Cell class does not specified cell action.

Methods used from Cake\Event\EventDispatcherTrait

dispatchEvent()source public

dispatchEvent( string $name , array|null $data = null , object|null $subject = null )

Wrapper for creating and dispatching events.

Returns a dispatched event.

Parameters

string $name
Name of the event.
array|null $data optional null

Any value you wish to be transported with this event to it can be read by listeners.

object|null $subject optional null

The object that this event applies to ($this by default).

Returns

Cake\Event\Event

eventManager()source public deprecated

eventManager( Cake\Event\EventManager $eventManager = null )

Returns the Cake\Event\EventManager manager instance for this object.

You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.

Deprecated

3.5.0 Use getEventManager()/setEventManager() instead.

Parameters

Cake\Event\EventManager $eventManager optional null
the eventManager to set

Returns

Cake\Event\EventManager

getEventManager()source public

getEventManager( )

Returns the Cake\Event\EventManager manager instance for this object.

You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.

Returns

Cake\Event\EventManager

setEventManager()source public

setEventManager( Cake\Event\EventManager $eventManager )

Returns the Cake\Event\EventManager manager instance for this object.

You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.

Parameters

Cake\Event\EventManager $eventManager
the eventManager to set

Returns


$this

Methods used from Cake\Log\LogTrait

log()source public

log( mixed $msg , integer|string $level = LogLevel::ERROR , string|array $context = [] )

Convenience method to write a message to Log. See Log::write() for more information on writing to logs.

Parameters

mixed $msg
Log message.
integer|string $level optional LogLevel::ERROR
Error level.
string|array $context optional []
Additional log data relevant to this message.

Returns

boolean
Success of log write.

Methods used from Cake\Routing\RequestActionTrait

requestAction()source public deprecated

requestAction( string|array $url , array $extra = [] )

Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.

Under the hood this method uses Router::reverse() to convert the $url parameter into a string URL. You should use URL formats that are compatible with Router::reverse()

Examples

A basic example getting the return value of the controller action:

$variables = $this->requestAction('/articles/popular');

A basic example of request action to fetch a rendered page without the layout.

$viewHtml = $this->requestAction('/articles/popular', ['return']);

You can also pass the URL as an array:

$vars = $this->requestAction(['controller' => 'articles', 'action' => 'popular']);

Passing other request data

You can pass POST, GET, COOKIE and other data into the request using the appropriate keys. Cookies can be passed using the cookies key. Get parameters can be set with query and post data can be sent using the post key.

$vars = $this->requestAction('/articles/popular', [
  'query' => ['page' => 1],
  'cookies' => ['remember_me' => 1],
]);

Sending environment or header values

By default actions dispatched with this method will use the global $_SERVER and $_ENV values. If you want to override those values for a request action, you can specify the values:

$vars = $this->requestAction('/articles/popular', [
  'environment' => ['CONTENT_TYPE' => 'application/json']
]);

Transmitting the session

By default actions dispatched with this method will use the standard session object. If you want a particular session instance to be used, you need to specify it.

$vars = $this->requestAction('/articles/popular', [
  'session' => new Session($someSessionConfig)
]);

Deprecated

3.3.0 You should refactor your code to use View Cells instead of this method.

Parameters

string|array $url

String or array-based url. Unlike other url arrays in CakePHP, this url will not automatically handle passed arguments in the $url parameter.

array $extra optional []

if array includes the key "return" it sets the autoRender to true. Can also be used to submit GET/POST data, and passed arguments.

Returns

mixed

Boolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.


Methods used from Cake\View\ViewVarsTrait

createView()source public

createView( string|null $viewClass = null )

Constructs the view class instance based on the current configuration.

Parameters

string|null $viewClass optional null
Optional namespaced class name of the View class to instantiate.

Returns

Cake\View\View

Throws

Cake\View\Exception\MissingViewException
If view class was not found.

set()source public

set( string|array $name , mixed $value = null )

Saves a variable or an associative array of variables for use inside a template.

Parameters

string|array $name
A string or an array of data.
mixed $value optional null

Value in case $name is a string (which then works as the key). Unused if $name is an associative array, otherwise serves as the values to $name's keys.

Returns


$this

viewBuilder()source public

viewBuilder( )

Get the view builder being used.

Returns

Cake\View\ViewBuilder

viewOptions()source public deprecated

viewOptions( string|array|null $options = null , boolean $merge = true )

Get/Set valid view options in the object's _validViewOptions property. The property is created as an empty array if it is not set. If called without any parameters it will return the current list of valid view options. See createView().

Deprecated

3.7.0 Use ViewBuilder::setOptions() or any one of it's setter methods instead.

Parameters

string|array|null $options optional null
string or array of string to be appended to _validViewOptions.
boolean $merge optional true

Whether to merge with or override existing valid View options. Defaults to true.

Returns

array
The updated view options as an array.

Magic methods inherited from Cake\Event\EventDispatcherInterface

getEventManager()

Properties detail

$Blockssource

protected Cake\View\ViewBlock

ViewBlock instance.

$_currentsource

protected string

The currently rendering view file. Used for resolving parent files.

$_currentTypesource

protected string

Currently rendering an element. Used for finding parent fragments for elements.

''

$_extsource

protected string

File extension. Defaults to CakePHP's template ".ctp".

'.ctp'

$_helperssource

protected Cake\View\HelperRegistry

Helpers collection

$_parentssource

protected array

The names of views and their parents used with View::extend();

[]

$_passedVarssource

protected array

List of variables to collect from the associated controller.

[
    'viewVars', 'autoLayout', 'helpers', 'template', 'layout', 'name', 'theme',
    'layoutPath', 'templatePath', 'plugin', 'passedArgs'
]

$_pathssource

protected array

Holds an array of paths.

[]

$_pathsForPluginsource

protected array

Holds an array of plugin paths.

[]

$_stacksource

protected array

Content stack, used for nested templates that all use View::extend();

[]

$_viewBlockClasssource

protected string

ViewBlock class.

ViewBlock::class

$autoLayoutsource

protected boolean

Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.

true

$elementCachesource

protected string

The Cache configuration View will use to store cached elements. Changing this will change the default configuration elements are stored under. You can also choose a cache config per element.

See

\Cake\View\View::element()
'default'

$hasRenderedsource

public boolean

True when the view has been rendered.

Deprecated

3.7.0 The property is deprecated and will be removed in 4.0.0.
false

$helperssource

protected array

An array of names of built-in helpers to include.

[]

$layoutsource

protected string

The name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.

'default'

$layoutPathsource

protected string

The name of the layouts subfolder containing layouts for this View.

$namesource

protected string

Name of the controller that created the View if any.

$passedArgssource

public array

Current passed params. Passed to View from the creating Controller for convenience.

Deprecated

3.1.0 Use $this->request->getParam('pass') instead.
[]

$pluginsource

protected string|null

The name of the plugin.

$requestsource

protected Cake\Http\ServerRequest

An instance of a \Cake\Http\ServerRequest object that contains information about the current request. This object contains all the information about a request and several methods for reading additional information about the request.

$responsesource

protected Cake\Http\Response

Reference to the Response object

$subDirsource

protected string

Sub-directory for this template file. This is often used for extension based routing. Eg. With an xml extension, $subDir would be xml/

''

$templatesource

protected string

The name of the template file to render. The name specified is the filename in /src/Template/ without the .ctp extension.

$templatePathsource

protected string

The name of the subfolder containing templates for this View.

$themesource

protected string|null

The view theme to use.

$uuidssource

public array

List of generated DOM UUIDs.

Deprecated

3.7.0 The property is deprecated and will be removed in 4.0.0.
[]

Magic properties detail

$Blockssource

public Cake\View\ViewBlock

$viewsource

public string

$viewPathsource

public string

© 2005–present The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/3.8/class-Cake.View.View.html