Class HtmlHelper
Html Helper class for easy use of HTML widgets.
HtmlHelper encloses all methods needed while working with HTML pages.
Property Summary
- 
        $Url public @propertyCake\View\Helper\UrlHelper
- 
        $_View protectedCake\View\ViewThe View instance this helper is attached to 
- 
        $_config protectedarrayRuntime config 
- 
        $_configInitialized protectedboolWhether the config property has already been configured with defaults 
- 
        $_defaultConfig protectedarrayDefault config for this class 
- 
        $_helperMap protectedarrayA helper lookup table used to lazy load helper objects. 
- 
        $_includedAssets protectedarrayNames of script & css files that have been included once 
- 
        $_scriptBlockOptions protectedarrayOptions for the currently opened script block buffer if any. 
- 
        $_templater protectedCake\View\StringTemplate|nullStringTemplate instance. 
- 
        $helpers protectedarrayList of helpers used by this helper 
Method Summary
- 
          __call() publicProvide non fatal errors on missing method calls. 
- 
          __construct() publicDefault Constructor 
- 
          __debugInfo() publicReturns an array that can be used to describe the internal state of this object. 
- 
          __get() publicLazy loads helpers. 
- 
          _configDelete() protectedDeletes a single config key. 
- 
          _configRead() protectedReads a config key. 
- 
          _configWrite() protectedWrites a config key. 
- 
          _confirm() protectedReturns a string to be used as onclick handler for confirm dialogs. 
- 
          _nestedListItem() protectedInternal function to build a nested list (UL/OL) out of an associative array. 
- 
          _renderCells() protectedRenders cells for a row of a table. 
- 
          addClass() publicAdds the given class to the element options 
- 
          charset() publicReturns a charset META-tag. 
- 
          configShallow() publicMerge provided config with existing config. Unlike config()which does a recursive merge for nested keys, this method does a simple merge.
- 
          css() publicCreates a link element for CSS stylesheets. 
- 
          div() publicReturns a formatted DIV tag for HTML FORMs. 
- 
          formatTemplate() publicFormats a template string with $data 
- 
          getConfig() publicReturns the config. 
- 
          getConfigOrFail() publicReturns the config for this specific key. 
- 
          getTemplates() publicGets templates to use or a specific template. 
- 
          getView() publicGet the view instance this helper is bound to. 
- 
          image() publicCreates a formatted IMG element. 
- 
          implementedEvents() publicEvent listeners. 
- 
          initialize() publicConstructor hook method. 
- 
          link() publicCreates an HTML link. 
- 
          linkFromPath() publicCreates an HTML link from route path string. 
- 
          media() publicReturns an audio/video element 
- 
          meta() publicCreates a link to an external resource and handles basic meta tags 
- 
          nestedList() publicBuild a nested list (UL/OL) out of an associative array. 
- 
          para() publicReturns a formatted P tag. 
- 
          script() publicReturns one or many <script>tags depending on the number of scripts given.
- 
          scriptBlock() publicWrap $script in a script tag. 
- 
          scriptEnd() publicEnd a Buffered section of JavaScript capturing. Generates a script tag inline or appends to specified view block depending on the settings used when the scriptBlock was started 
- 
          scriptStart() publicBegin a script block that captures output until HtmlHelper::scriptEnd() is called. This capturing block will capture all output between the methods and create a scriptBlock from it. 
- 
          setConfig() publicSets the config. 
- 
          setTemplates() publicSets templates to use. 
- 
          style() publicBuilds CSS style data from an array of CSS properties 
- 
          tableCell() publicRenders a single table cell (A TD with attributes). 
- 
          tableCells() publicReturns a formatted string of table rows (TR's with TD's in them). 
- 
          tableHeaders() publicReturns a row of formatted and named TABLE headers. 
- 
          tableRow() publicRenders a single table row (A TR with attributes). 
- 
          tag() publicReturns a formatted block tag, i.e DIV, SPAN, P. 
- 
          templater() publicReturns the templater instance. 
Method Detail
__call() ¶ public
__call(string $method, array $params): mixed|voidProvide non fatal errors on missing method calls.
Parameters
- 
                string$method
- Method to invoke 
- 
                array$params
- Array of params for the method. 
Returns
mixed|void__construct() ¶ public
__construct(Cake\View\View $view, array $config = [])Default Constructor
Parameters
- 
                Cake\View\View$view
- The View this helper is being attached to. 
- 
                array$config optional
- Configuration settings for the helper. 
__debugInfo() ¶ public
__debugInfo(): arrayReturns an array that can be used to describe the internal state of this object.
Returns
array__get() ¶ public
__get(string $name): Cake\View\Helper|null|voidLazy loads helpers.
Parameters
- 
                string$name
- Name of the property being accessed. 
Returns
Cake\View\Helper|null|voidHelper instance if helper with provided name exists
_configDelete() ¶ protected
_configDelete(string $key): voidDeletes a single config key.
Parameters
- 
                string$key
- Key to delete. 
Returns
voidThrows
Cake\Core\Exception\CakeExceptionif attempting to clobber existing config
_configRead() ¶ protected
_configRead(string|null $key): mixedReads a config key.
Parameters
- 
                string|null$key
- Key to read. 
Returns
mixed_configWrite() ¶ protected
_configWrite(string|array $key, mixed $value, bool|string $merge = false): voidWrites a config key.
Parameters
- 
                string|array$key
- Key to write to. 
- 
                mixed$value
- Value to write. 
- 
                bool|string$merge optional
- True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false. 
Returns
voidThrows
Cake\Core\Exception\CakeExceptionif attempting to clobber existing config
_confirm() ¶ protected
_confirm(string $okCode, string $cancelCode): stringReturns a string to be used as onclick handler for confirm dialogs.
Parameters
- 
                string$okCode
- Code to be executed after user chose 'OK' 
- 
                string$cancelCode
- Code to be executed after user chose 'Cancel' 
Returns
string"onclick" JS code
_nestedListItem() ¶ protected
_nestedListItem(array $items, array $options, array $itemOptions): stringInternal function to build a nested list (UL/OL) out of an associative array.
Parameters
- 
                array$items
- Set of elements to list. 
- 
                array$options
- Additional HTML attributes of the list (ol/ul) tag. 
- 
                array$itemOptions
- Options and additional HTML attributes of the list item (LI) tag. 
Returns
stringThe nested list element
See Also
_renderCells() ¶ protected
_renderCells(array $line, bool $useCount = false): string[]Renders cells for a row of a table.
This is a helper method for tableCells(). Overload this method as you need to change the behavior of the cell rendering.
Parameters
- 
                array$line
- Line data to render. 
- 
                bool$useCount optional
- Renders the count into the row. Default is false. 
Returns
string[]addClass() ¶ public
addClass(array $options, string $class, string $key = 'class'): arrayAdds the given class to the element options
Parameters
- 
                array$options
- Array options/attributes to add a class to 
- 
                string$class
- The class name being added. 
- 
                string$key optional
- the key to use for class. Defaults to - 'class'.
Returns
arrayArray of options with $key set.
charset() ¶ public
charset(string|null $charset = null): stringReturns a charset META-tag.
Parameters
- 
                string|null$charset optional
- The character set to be used in the meta tag. If empty, The App.encoding value will be used. Example: "utf-8". 
Returns
stringA meta tag containing the specified character set.
Links
configShallow() ¶ public
configShallow(string|array $key, mixed|null $value = null): $thisMerge provided config with existing config. Unlike config() which does
a recursive merge for nested keys, this method does a simple merge.
Setting a specific value:
$this->configShallow('key', $value);Setting a nested value:
$this->configShallow('some.nested.key', $value);Updating multiple config settings at the same time:
$this->configShallow(['one' => 'value', 'another' => 'value']);Parameters
- 
                string|array$key
- The key to set, or a complete array of configs. 
- 
                mixed|null$value optional
- The value to set. 
Returns
$thiscss() ¶ public
css(string|string[] $path, array $options = []): string|nullCreates a link element for CSS stylesheets.
Usage
Include one CSS file:
echo $this->Html->css('styles.css');Include multiple CSS files:
echo $this->Html->css(['one.css', 'two.css']);Add the stylesheet to view block "css":
$this->Html->css('styles.css', ['block' => true]);Add the stylesheet to a custom block:
$this->Html->css('styles.css', ['block' => 'layoutCss']);Options
- blockSet to true to append output to view block "css" or provide custom block name.
- onceWhether or not the css file should be checked for uniqueness. If true css files will only be included once, use false to allow the same css to be included more than once per request.
- pluginFalse value will prevent parsing path as a plugin
- relDefaults to 'stylesheet'. If equal to 'import' the stylesheet will be imported.
- fullBaseIf true the URL will get a full address for the css file.
Parameters
- 
                string|string[]$path
- The name of a CSS style sheet or an array containing names of CSS stylesheets. If - $pathis prefixed with '/', the path will be relative to the webroot of your application. Otherwise, the path will be relative to your CSS path, usually webroot/css.
- 
                array$options optional
- Array of options and HTML arguments. 
Returns
string|nullCSS <link /> or <style /> tag, depending on the type of link.
Links
div() ¶ public
div(string|null $class = null, string|null $text = null, array $options = []): stringReturns a formatted DIV tag for HTML FORMs.
Options
- escapeWhether or not the contents should be html_entity escaped.
Parameters
- 
                string|null$class optional
- CSS class name of the div element. 
- 
                string|null$text optional
- String content that will appear inside the div element. If null, only a start tag will be printed 
- 
                array$options optional
- Additional HTML attributes of the DIV tag 
Returns
stringThe formatted DIV element
formatTemplate() ¶ public
formatTemplate(string $name, array $data): stringFormats a template string with $data
Parameters
- 
                string$name
- The template name. 
- 
                array$data
- The data to insert. 
Returns
stringgetConfig() ¶ public
getConfig(string|null $key = null, mixed $default = null): mixedReturns the config.
Usage
Reading the whole config:
$this->getConfig();Reading a specific value:
$this->getConfig('key');Reading a nested value:
$this->getConfig('some.nested.key');Reading with default value:
$this->getConfig('some-key', 'default-value');Parameters
- 
                string|null$key optional
- The key to get or null for the whole config. 
- 
                mixed$default optional
- The return value when the key does not exist. 
Returns
mixedConfiguration data at the named key or null if the key does not exist.
getConfigOrFail() ¶ public
getConfigOrFail(string $key): mixedReturns the config for this specific key.
The config value for this key must exist, it can never be null.
Parameters
- 
                string$key
- The key to get. 
Returns
mixedConfiguration data at the named key
Throws
InvalidArgumentExceptiongetTemplates() ¶ public
getTemplates(string|null $template = null): string|arrayGets templates to use or a specific template.
Parameters
- 
                string|null$template optional
- String for reading a specific template, null for all. 
Returns
string|arraygetView() ¶ public
getView(): Cake\View\ViewGet the view instance this helper is bound to.
Returns
Cake\View\ViewThe bound view instance.
image() ¶ public
image(string|array $path, array $options = []): stringCreates a formatted IMG element.
This method will set an empty alt attribute if one is not supplied.
Usage:
Create a regular image:
echo $this->Html->image('cake_icon.png', ['alt' => 'CakePHP']);Create an image link:
echo $this->Html->image('cake_icon.png', ['alt' => 'CakePHP', 'url' => 'https://cakephp.org']);Options:
- urlIf provided an image link will be generated and the link will point at- $options['url'].
- fullBaseIf true the src attribute will get a full address for the image file.
- pluginFalse value will prevent parsing path as a plugin
Parameters
- 
                string|array$path
- Path to the image file, relative to the webroot/img/ directory. 
- 
                array$options optional
- Array of HTML attributes. See above for special options. 
Returns
stringcompleted img tag
Links
implementedEvents() ¶ public
implementedEvents(): arrayEvent listeners.
By defining one of the callback methods a helper is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want helpers to listen to non-standard events.
Returns
arrayinitialize() ¶ public
initialize(array $config): voidConstructor hook method.
Implement this method to avoid having to overwrite the constructor and call parent.
Parameters
- 
                array$config
- The configuration settings provided to this helper. 
Returns
voidlink() ¶ public
link(string|array $title, string|array|null $url = null, array $options = []): stringCreates an HTML link.
If $url starts with "http://" this is treated as an external link. Else, it is treated as a path to controller/action and parsed with the UrlHelper::build() method.
If the $url is empty, $title is used instead.
Options
- escapeSet to false to disable escaping of title and attributes.
- escapeTitleSet to false to disable escaping of title. Takes precedence over value of- escape)
- confirmJavaScript confirmation message.
Parameters
- 
                string|array$title
- The content to be wrapped by - <a>tags. Can be an array if $url is null. If $url is null, $title will be used as both the URL and title.
- 
                string|array|null$url optional
- Cake-relative URL or array of URL parameters, or external URL (starts with http://) 
- 
                array$options optional
- Array of options and HTML attributes. 
Returns
stringAn <a /> element.
Links
linkFromPath() ¶ public
linkFromPath(string $title, string $path, array $params = [], array $options = []): stringCreates an HTML link from route path string.
Options
- escapeSet to false to disable escaping of title and attributes.
- escapeTitleSet to false to disable escaping of title. Takes precedence over value of- escape)
- confirmJavaScript confirmation message.
Parameters
- 
                string$title
- The content to be wrapped by - <a>tags.
- 
                string$path
- Cake-relative route path. 
- 
                array$params optional
- An array specifying any additional parameters. Can be also any special parameters supported by - Router::url().
- 
                array$options optional
- Array of options and HTML attributes. 
Returns
stringAn <a /> element.
See Also
Links
media() ¶ public
media(string|array $path, array $options = []): stringReturns an audio/video element
Usage
Using an audio file:
echo $this->Html->media('audio.mp3', ['fullBase' => true]);Outputs:
<video src="http://www.somehost.com/files/audio.mp3">Fallback text</video>Using a video file:
echo $this->Html->media('video.mp4', ['text' => 'Fallback text']);Outputs:
<video src="/files/video.mp4">Fallback text</video>Using multiple video files:
echo $this->Html->media(
     ['video.mp4', ['src' => 'video.ogv', 'type' => "video/ogg; codecs='theora, vorbis'"]],
     ['tag' => 'video', 'autoplay']
);Outputs:
<video autoplay="autoplay">
     <source src="/files/video.mp4" type="video/mp4"/>
     <source src="/files/video.ogv" type="video/ogv; codecs='theora, vorbis'"/>
</video>Options
- tagType of media element to generate, either "audio" or "video". If tag is not provided it's guessed based on file's mime type.
- textText to include inside the audio/video tag
- pathPrefixPath prefix to use for relative URLs, defaults to 'files/'
- fullBaseIf provided the src attribute will get a full address including domain name
Parameters
- 
                string|array$path
- Path to the video file, relative to the webroot/{$options['pathPrefix']} directory. Or an array where each item itself can be a path string or an associate array containing keys - srcand- type
- 
                array$options optional
- Array of HTML attributes, and special options above. 
Returns
stringGenerated media element
meta() ¶ public
meta(string|array $type, string|array|null $content = null, array $options = []): string|nullCreates a link to an external resource and handles basic meta tags
Create a meta tag that is output inline:
$this->Html->meta('icon', 'favicon.ico');Append the meta tag to custom view block "meta":
$this->Html->meta('description', 'A great page', ['block' => true]);Append the meta tag to custom view block:
$this->Html->meta('description', 'A great page', ['block' => 'metaTags']);Create a custom meta tag:
$this->Html->meta(['property' => 'og:site_name', 'content' => 'CakePHP']);Options
- block- Set to true to append output to view block "meta" or provide custom block name.
Parameters
- 
                string|array$type
- The title of the external resource, Or an array of attributes for a custom meta tag. 
- 
                string|array|null$content optional
- The address of the external resource or string for content attribute 
- 
                array$options optional
- Other attributes for the generated tag. If the type attribute is html, rss, atom, or icon, the mime-type is returned. 
Returns
string|nullA completed <link /> element, or null if the element was sent to a block.
Links
nestedList() ¶ public
nestedList(array $list, array $options = [], array $itemOptions = []): stringBuild a nested list (UL/OL) out of an associative array.
Options for $options:
- tag- Type of list tag to use (ol/ul)
Options for $itemOptions:
- even- Class to use for even rows.
- odd- Class to use for odd rows.
Parameters
- 
                array$list
- Set of elements to list 
- 
                array$options optional
- Options and additional HTML attributes of the list (ol/ul) tag. 
- 
                array$itemOptions optional
- Options and additional HTML attributes of the list item (LI) tag. 
Returns
stringThe nested list
Links
para() ¶ public
para(string|null $class, string|null $text, array $options = []): stringReturns a formatted P tag.
Options
- escapeWhether or not the contents should be html_entity escaped.
Parameters
- 
                string|null$class
- CSS class name of the p element. 
- 
                string|null$text
- String content that will appear inside the p element. 
- 
                array$options optional
- Additional HTML attributes of the P tag 
Returns
stringThe formatted P element
script() ¶ public
script(string|string[] $url, array $options = []): string|nullReturns one or many <script> tags depending on the number of scripts given.
If the filename is prefixed with "/", the path will be relative to the base path of your application. Otherwise, the path will be relative to your JavaScript path, usually webroot/js.
Usage
Include one script file:
echo $this->Html->script('styles.js');Include multiple script files:
echo $this->Html->script(['one.js', 'two.js']);Add the script file to a custom block:
$this->Html->script('styles.js', ['block' => 'bodyScript']);Options
- blockSet to true to append output to view block "script" or provide custom block name.
- onceWhether or not the script should be checked for uniqueness. If true scripts will only be included once, use false to allow the same script to be included more than once per request.
- pluginFalse value will prevent parsing path as a plugin
- fullBaseIf true the url will get a full address for the script file.
Parameters
- 
                string|string[]$url
- String or array of javascript files to include 
- 
                array$options optional
- Array of options, and html attributes see above. 
Returns
string|nullString of <script /> tags or null if block is specified in options
or if $once is true and the file has been included before.
Links
scriptBlock() ¶ public
scriptBlock(string $script, array $options = []): string|nullWrap $script in a script tag.
Options
- blockSet to true to append output to view block "script" or provide custom block name.
Parameters
- 
                string$script
- The script to wrap 
- 
                array$options optional
- The options to use. Options not listed above will be treated as HTML attributes. 
Returns
string|nullString or null depending on the value of $options['block']
Links
scriptEnd() ¶ public
scriptEnd(): string|nullEnd a Buffered section of JavaScript capturing. Generates a script tag inline or appends to specified view block depending on the settings used when the scriptBlock was started
Returns
string|nullDepending on the settings of scriptStart() either a script tag or null
Links
scriptStart() ¶ public
scriptStart(array $options = []): voidBegin a script block that captures output until HtmlHelper::scriptEnd() is called. This capturing block will capture all output between the methods and create a scriptBlock from it.
Options
- blockSet to true to append output to view block "script" or provide custom block name.
Parameters
- 
                array$options optional
- Options for the code block. 
Returns
voidLinks
setConfig() ¶ public
setConfig(string|array $key, mixed|null $value = null, bool $merge = true): $thisSets the config.
Usage
Setting a specific value:
$this->setConfig('key', $value);Setting a nested value:
$this->setConfig('some.nested.key', $value);Updating multiple config settings at the same time:
$this->setConfig(['one' => 'value', 'another' => 'value']);Parameters
- 
                string|array$key
- The key to set, or a complete array of configs. 
- 
                mixed|null$value optional
- The value to set. 
- 
                bool$merge optional
- Whether to recursively merge or overwrite existing config, defaults to true. 
Returns
$thisThrows
Cake\Core\Exception\CakeExceptionWhen trying to set a key that is invalid.
setTemplates() ¶ public
setTemplates(string[] $templates): $thisSets templates to use.
Parameters
- 
                string[]$templates
- Templates to be added. 
Returns
$thisstyle() ¶ public
style(array $data, bool $oneLine = true): stringBuilds CSS style data from an array of CSS properties
Usage:
echo $this->Html->style(['margin' => '10px', 'padding' => '10px'], true);
// creates
'margin:10px;padding:10px;'Parameters
- 
                array$data
- Style data array, keys will be used as property names, values as property values. 
- 
                bool$oneLine optional
- Whether or not the style block should be displayed on one line. 
Returns
stringCSS styling data
Links
tableCell() ¶ public
tableCell(string $content, array $options = []): stringRenders a single table cell (A TD with attributes).
Parameters
- 
                string$content
- The content of the cell. 
- 
                array$options optional
- HTML attributes. 
Returns
stringtableCells() ¶ public
tableCells(array|string $data, array|bool|null $oddTrOptions = null, array|bool|null $evenTrOptions = null, bool $useCount = false, bool $continueOddEven = true): stringReturns a formatted string of table rows (TR's with TD's in them).
Parameters
- 
                array|string$data
- Array of table data 
- 
                array|bool|null$oddTrOptions optional
- HTML options for odd TR elements if true useCount is used 
- 
                array|bool|null$evenTrOptions optional
- HTML options for even TR elements 
- 
                bool$useCount optional
- adds class "column-$i" 
- 
                bool$continueOddEven optional
- If false, will use a non-static $count variable, so that the odd/even count is reset to zero just for that call. 
Returns
stringFormatted HTML
Links
tableHeaders() ¶ public
tableHeaders(array $names, array|null $trOptions = null, array|null $thOptions = null): stringReturns a row of formatted and named TABLE headers.
Parameters
- 
                array$names
- Array of tablenames. Each tablename can be string, or array with name and an array with a set of attributes to its specific tag 
- 
                array|null$trOptions optional
- HTML options for TR elements. 
- 
                array|null$thOptions optional
- HTML options for TH elements. 
Returns
stringCompleted table headers
Links
tableRow() ¶ public
tableRow(string $content, array $options = []): stringRenders a single table row (A TR with attributes).
Parameters
- 
                string$content
- The content of the row. 
- 
                array$options optional
- HTML attributes. 
Returns
stringtag() ¶ public
tag(string $name, string|null $text = null, array $options = []): stringReturns a formatted block tag, i.e DIV, SPAN, P.
Options
- escapeWhether or not the contents should be html_entity escaped.
Parameters
- 
                string$name
- Tag name. 
- 
                string|null$text optional
- String content that will appear inside the div element. If null, only a start tag will be printed 
- 
                array$options optional
- Additional HTML attributes of the DIV tag, see above. 
Returns
stringThe formatted tag element
templater() ¶ public
templater(): Cake\View\StringTemplateReturns the templater instance.
Returns
Cake\View\StringTemplate