Page Contents
- Html
HtmlHelper
- Inserting Well-Formatted Elements
- Changing the Tags Output by HtmlHelper
This document is for CakePHP's development version, which can be significantly different
from previous releases.
You may want to read
current stable release documentation instead.
HtmlHelper
The role of the HtmlHelper in CakePHP is to make HTML-related options easier, faster, and more resilient to change. Using this helper will enable your application to be more light on its feet, and more flexible on where it is placed in relation to the root of a domain.
Many HtmlHelper methods include a $attributes
parameter,
that allow you to tack on any extra attributes on your tags. Here
are a few examples of how to use the $attributes
parameter:
Desired attributes: <tag class="someClass" />
Array parameter: ['class' => 'someClass']
Desired attributes: <tag name="foo" value="bar" />
Array parameter: ['name' => 'foo', 'value' => 'bar']
The most important task the HtmlHelper accomplishes is creating well formed markup. This section will cover some of the methods of the HtmlHelper and how to use them.
Creates a link(s) to a CSS style-sheet. If the block
option is set to
true
, the link tags are added to the css
block which you can print
inside the head tag of the document.
You can use the block
option to control which block the link element
will be appended to. By default it will append to the css
block.
If key ‘rel’ in $options
array is set to ‘import’ the stylesheet will be imported.
This method of CSS inclusion assumes that the CSS file specified resides inside the webroot/css directory if path doesn’t start with a ‘/’.
echo $this->Html->css('forms');
Will output:
<link rel="stylesheet" href="/css/forms.css" />
The first parameter can be an array to include multiple files.
echo $this->Html->css(['forms', 'tables', 'menu']);
Will output:
<link rel="stylesheet" href="/css/forms.css" />
<link rel="stylesheet" href="/css/tables.css" />
<link rel="stylesheet" href="/css/menu.css" />
You can include CSS files from any loaded plugin using plugin syntax. To include plugins/DebugKit/webroot/css/toolbar.css you could use the following:
echo $this->Html->css('DebugKit.toolbar.css');
If you want to include a CSS file which shares a name with a loaded
plugin you can do the following. For example if you had a Blog
plugin,
and also wanted to include webroot/css/Blog.common.css, you would:
echo $this->Html->css('Blog.common.css', ['plugin' => false]);
Builds CSS style definitions based on the keys and values of the array passed to the method. Especially handy if your CSS file is dynamic.
echo $this->Html->style([
'background' => '#633',
'border-bottom' => '1px solid #000',
'padding' => '10px'
]);
Will output:
background:#633; border-bottom:1px solid #000; padding:10px;
Creates a formatted image tag. The path supplied should be relative to webroot/img/.
echo $this->Html->image('cake_logo.png', ['alt' => 'CakePHP']);
Will output:
<img src="/img/cake_logo.png" alt="CakePHP" />
To create an image link specify the link destination using the
url
option in $attributes
.
echo $this->Html->image("recipes/6.jpg", [
"alt" => "Brownies",
'url' => ['controller' => 'Recipes', 'action' => 'view', 6]
]);
Will output:
<a href="/recipes/view/6">
<img src="/img/recipes/6.jpg" alt="Brownies" />
</a>
If you are creating images in emails, or want absolute paths to images you
can use the fullBase
option:
echo $this->Html->image("logo.png", ['fullBase' => true]);
Will output:
<img src="http://example.com/img/logo.jpg" alt="" />
You can include image files from any loaded plugin using plugin syntax. To include plugins/DebugKit/webroot/img/icon.png You could use the following:
echo $this->Html->image('DebugKit.icon.png');
If you want to include an image file which shares a name with a loaded
plugin you can do the following. For example if you had a Blog
plugin,
and also wanted to include webroot/img/Blog.icon.png, you would:
echo $this->Html->image('Blog.icon.png', ['plugin' => false]);
If you would like the prefix of the URL to not be /img
, you can override this setting by specifying the prefix in the $options
array
echo $this->Html->image("logo.png", ['pathPrefix' => '']);
Will output:
<img src="logo.jpg" alt="" />
General purpose method for creating HTML links. Use $options
to
specify attributes for the element and whether or not the
$title
should be escaped.
echo $this->Html->link(
'Enter',
'/pages/home',
['class' => 'button', 'target' => '_blank']
);
Will output:
<a href="/pages/home" class="button" target="_blank">Enter</a>
Use '_full'=>true
option for absolute URLs:
echo $this->Html->link(
'Dashboard',
['controller' => 'Dashboards', 'action' => 'index', '_full' => true]
);
Will output:
<a href="http://www.yourdomain.com/dashboards/index">Dashboard</a>
Specify confirm
key in options to display a JavaScript confirm()
dialog:
echo $this->Html->link(
'Delete',
['controller' => 'Recipes', 'action' => 'delete', 6],
['confirm' => 'Are you sure you wish to delete this recipe?']
);
Will output:
<a href="/recipes/delete/6"
onclick="return confirm(
'Are you sure you wish to delete this recipe?'
);">
Delete
</a>
Query strings can also be created with link()
.
echo $this->Html->link('View image', [
'controller' => 'Images',
'action' => 'view',
1,
'?' => ['height' => 400, 'width' => 500]
]);
Will output:
<a href="/images/view/1?height=400&width=500">View image</a>
HTML special characters in $title
will be converted to HTML
entities. To disable this conversion, set the escape option to
false
in the $options
array.
echo $this->Html->link(
$this->Html->image("recipes/6.jpg", ["alt" => "Brownies"]),
"recipes/view/6",
['escape' => false]
);
Will output:
<a href="/recipes/view/6">
<img src="/img/recipes/6.jpg" alt="Brownies" />
</a>
Setting escape
to false
will also disable escaping of attributes of the
link. You can use the option escapeTitle
to disable just
escaping of title and not the attributes.
echo $this->Html->link(
$this->Html->image('recipes/6.jpg', ['alt' => 'Brownies']),
'recipes/view/6',
['escapeTitle' => false, 'title' => 'hi "howdy"']
);
Will output:
<a href="/recipes/view/6" title="hi "howdy"">
<img src="/img/recipes/6.jpg" alt="Brownies" />
</a>
Also check Cake\View\Helper\UrlHelper::build()
method
for more examples of different types of URLs.
If you want to use route path strings, you can do that using this method:
echo $this->Html->linkFromPath('Index', 'Articles::index');
// outputs: <a href="/articles">Index</a>
echo $this->Html->linkFromPath('View', 'MyBackend.Admin/Articles::view', [3]);
// outputs: <a href="/admin/my-backend/articles/view/3">View</a>
New in version 4.1.0: linkFromPath()
was added.
Options:
type
Type of media element to generate, valid values are “audio”
or “video”. If type is not provided media type is guessed based on
file’s mime type.
text
Text to include inside the video tag
pathPrefix
Path prefix to use for relative URLs, defaults to
‘files/’
fullBase
If provided the src attribute will get a full address
including domain name
Returns a formatted audio/video tag:
<?= $this->Html->media('audio.mp3') ?>
// Output
<audio src="/files/audio.mp3"></audio>
<?= $this->Html->media('video.mp4', [
'fullBase' => true,
'text' => 'Fallback text'
]) ?>
// Output
<video src="http://www.somehost.com/files/video.mp4">Fallback text</video>
<?= $this->Html->media(
['video.mp4', ['src' => 'video.ogg', 'type' => "video/ogg; codecs='theora, vorbis'"]],
['autoplay']
) ?>
// Output
<video autoplay="autoplay">
<source src="/files/video.mp4" type="video/mp4"/>
<source src="/files/video.ogg" type="video/ogg;
codecs='theora, vorbis'"/>
</video>
Include a script file(s), contained either locally or as a remote URL.
By default, script tags are added to the document inline. If you override
this by setting $options['block']
to true
, the script tags will instead
be added to the script
block which you can print elsewhere in the document.
If you wish to override which block name is used, you can do so by setting
$options['block']
.
$options['once']
controls whether or
not you want to include this script once per request or more than
once. This defaults to true
.
You can use $options to set additional properties to the generated script tag. If an array of script tags is used, the attributes will be applied to all of the generated script tags.
This method of JavaScript file inclusion assumes that the JavaScript file specified resides inside the webroot/js directory:
echo $this->Html->script('scripts');
Will output:
<script src="/js/scripts.js"></script>
You can link to files with absolute paths as well to link files that are not in webroot/js:
echo $this->Html->script('/otherdir/script_file');
You can also link to a remote URL:
echo $this->Html->script('https://code.jquery.com/jquery.min.js');
Will output:
<script src="https://code.jquery.com/jquery.min.js"></script>
The first parameter can be an array to include multiple files.
echo $this->Html->script(['jquery', 'wysiwyg', 'scripts']);
Will output:
<script src="/js/jquery.js"></script>
<script src="/js/wysiwyg.js"></script>
<script src="/js/scripts.js"></script>
You can append the script tag to a specific block using the block
option:
$this->Html->script('wysiwyg', ['block' => 'scriptBottom']);
In your layout you can output all the script tags added to ‘scriptBottom’:
echo $this->fetch('scriptBottom');
You can include script files from any loaded plugin using plugin syntax. To include plugins/DebugKit/webroot/js/toolbar.js You could use the following:
echo $this->Html->script('DebugKit.toolbar.js');
If you want to include a script file which shares a name with a loaded
plugin you can do the following. For example if you had a Blog
plugin,
and also wanted to include webroot/js/Blog.plugins.js, you would:
echo $this->Html->script('Blog.plugins.js', ['plugin' => false]);
To generate Javascript blocks from PHP view code, you can use one of the script block methods. Scripts can either be output in place, or buffered into a block:
// Define a script block all at once, with the defer attribute.
$this->Html->scriptBlock('alert("hi")', ['defer' => true]);
// Buffer a script block to be output later.
$this->Html->scriptBlock('alert("hi")', ['block' => true]);
You can use the scriptStart()
method to create a capturing block that will
output into a <script>
tag. Captured script snippets can be output inline,
or buffered into a block:
// Append into the 'script' block.
$this->Html->scriptStart(['block' => true]);
echo "alert('I am in the JavaScript');";
$this->Html->scriptEnd();
Once you have buffered javascript, you can output it as you would any other View Block:
// In your layout
echo $this->fetch('script');
Build a nested list (UL/OL) out of an associative array:
$list = [
'Languages' => [
'English' => [
'American',
'Canadian',
'British',
],
'Spanish',
'German',
]
];
echo $this->Html->nestedList($list);
Output:
// Output (minus the whitespace)
<ul>
<li>Languages
<ul>
<li>English
<ul>
<li>American</li>
<li>Canadian</li>
<li>British</li>
</ul>
</li>
<li>Spanish</li>
<li>German</li>
</ul>
</li>
</ul>
Creates a row of table header cells to be placed inside of <table> tags.
echo $this->Html->tableHeaders(['Date', 'Title', 'Active']);
Output:
<tr>
<th>Date</th>
<th>Title</th>
<th>Active</th>
</tr>
echo $this->Html->tableHeaders(
['Date', 'Title','Active'],
['class' => 'status'],
['class' => 'product_table']
);
Output:
<tr class="status">
<th class="product_table">Date</th>
<th class="product_table">Title</th>
<th class="product_table">Active</th>
</tr>
You can set attributes per column, these are used instead of the
defaults provided in the $thOptions
:
echo $this->Html->tableHeaders([
'id',
['Name' => ['class' => 'highlight']],
['Date' => ['class' => 'sortable']]
]);
Output:
<tr>
<th>id</th>
<th class="highlight">Name</th>
<th class="sortable">Date</th>
</tr>
Creates table cells, in rows, assigning <tr> attributes differently for odd- and even-numbered rows. Wrap a single table cell within an [] for specific <td>-attributes.
echo $this->Html->tableCells([
['Jul 7th, 2007', 'Best Brownies', 'Yes'],
['Jun 21st, 2007', 'Smart Cookies', 'Yes'],
['Aug 1st, 2006', 'Anti-Java Cake', 'No'],
]);
Output:
<tr><td>Jul 7th, 2007</td><td>Best Brownies</td><td>Yes</td></tr>
<tr><td>Jun 21st, 2007</td><td>Smart Cookies</td><td>Yes</td></tr>
<tr><td>Aug 1st, 2006</td><td>Anti-Java Cake</td><td>No</td></tr>
echo $this->Html->tableCells([
['Jul 7th, 2007', ['Best Brownies', ['class' => 'highlight']] , 'Yes'],
['Jun 21st, 2007', 'Smart Cookies', 'Yes'],
['Aug 1st, 2006', 'Anti-Java Cake', ['No', ['id' => 'special']]],
]);
Output:
<tr>
<td>
Jul 7th, 2007
</td>
<td class="highlight">
Best Brownies
</td>
<td>
Yes
</td>
</tr>
<tr>
<td>
Jun 21st, 2007
</td>
<td>
Smart Cookies
</td>
<td>
Yes
</td>
</tr>
<tr>
<td>
Aug 1st, 2006
</td>
<td>
Anti-Java Cake
</td>
<td id="special">
No
</td>
</tr>
echo $this->Html->tableCells(
[
['Red', 'Apple'],
['Orange', 'Orange'],
['Yellow', 'Banana'],
],
['class' => 'darker']
);
Output:
<tr class="darker"><td>Red</td><td>Apple</td></tr>
<tr><td>Orange</td><td>Orange</td></tr>
<tr class="darker"><td>Yellow</td><td>Banana</td></tr>