Skip to content

Commit fe1aa0d

Browse files
authored
Document trusted HTML values (#8386)
* Document trusted HTML values and helper support * Address trusted HTML documentation review feedback
1 parent 815e98a commit fe1aa0d

5 files changed

Lines changed: 231 additions & 26 deletions

File tree

‎docs/en/appendices/6-0-migration-guide.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,3 +355,12 @@ still uses other Diactoros classes or functions, declare
355355
classes and actions using PHP attributes such as `#[Get]`, `#[Post]`, `#[Scope]`,
356356
`#[Resource]`, and more. See [Attribute Routing](../development/attribute-routing)
357357
for full documentation.
358+
359+
### View
360+
361+
- `HtmlString` and the `Cake\View\html()` function wrap trusted markup, while
362+
`HtmlString::render()` escapes ordinary strings and preserves values
363+
implementing the new `HtmlStringable` interface. Supported HtmlHelper and
364+
FormHelper content arguments accept these values without disabling escaping.
365+
See [Rendering Trusted HTML](../views#rendering-trusted-html) for usage and
366+
escaping rules.

‎docs/en/core-libraries/global-constants-and-functions.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,10 @@ distribute the code), since it's a full emulation wrapper.
183183

184184
Convenience wrapper for `htmlspecialchars()`.
185185

186+
This function also escapes `Cake\View\HtmlStringable` values. To escape
187+
ordinary strings while preserving trusted HTML, use
188+
[`HtmlString::render()`](../views#rendering-trusted-html).
189+
186190
### pluginSplit()
187191

188192
`function` **pluginSplit(string $name, boolean $dotAppend = false, string $plugin = null)**
@@ -200,6 +204,29 @@ Split the namespace from the classname.
200204

201205
Commonly used like `list($namespace, $className) = namespaceSplit('Cake\Core\App');`
202206

207+
## View Functions
208+
209+
### html()
210+
211+
`function` Cake\\View\\**html(string $html): HtmlString**
212+
213+
Wraps trusted markup in an immutable `Cake\View\HtmlString` value. Import
214+
the namespaced function before using it:
215+
216+
```php
217+
use function Cake\View\html;
218+
219+
echo $this->Html->link(html('<strong>Read more</strong>'), '/articles');
220+
```
221+
222+
This function marks a string as trusted content and does not sanitize it. See
223+
[Rendering Trusted HTML](../views#rendering-trusted-html) for escaping rules,
224+
helper support, and custom implementations.
225+
226+
::: info Added in version 6.0.0
227+
The `Cake\View\html()` function was added.
228+
:::
229+
203230
## Core Definition Constants
204231

205232
Most of the following constants refer to paths in your application.

‎docs/en/views.md‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,105 @@ the `h()` function:
157157
<?= h($user->bio); ?>
158158
```
159159

160+
### Rendering Trusted HTML
161+
162+
When a value can contain either plain text or HTML intended to render directly,
163+
use `Cake\View\HtmlString` to distinguish trusted markup from text that needs
164+
escaping. `HtmlString` is an immutable value object:
165+
166+
```php
167+
use Cake\View\HtmlString;
168+
use function Cake\View\html;
169+
170+
$content = new HtmlString('<strong>Featured article</strong>');
171+
172+
// The html() convenience function creates the same value object.
173+
$content = html('<strong>Featured article</strong>');
174+
175+
echo $content;
176+
// <strong>Featured article</strong>
177+
```
178+
179+
`HtmlString` marks markup as trusted; it does not sanitize it. Only wrap HTML
180+
you control, and escape any untrusted values before including them:
181+
182+
```php
183+
$content = html('<strong>' . h($article->title) . '</strong>');
184+
```
185+
186+
Use `HtmlString::render()` in templates or custom renderers that accept either
187+
a string or an `HtmlStringable` value. It escapes ordinary strings with `h()`
188+
and renders trusted HTML unchanged:
189+
190+
```php
191+
echo HtmlString::render('News & updates');
192+
// News &amp; updates
193+
194+
echo HtmlString::render(html('<strong>News</strong>'));
195+
// <strong>News</strong>
196+
```
197+
198+
An explicit call to `h()` still escapes trusted markup:
199+
200+
```php
201+
echo h(html('<strong>News</strong>'));
202+
// &lt;strong&gt;News&lt;/strong&gt;
203+
```
204+
205+
Casting an `HtmlString` to a string returns its original markup. It also
206+
implements `JsonSerializable`, so `json_encode()` serializes it as a JSON string.
207+
208+
#### Using Trusted HTML with Helpers
209+
210+
The [HtmlHelper](views/helpers/html#creating-links) and
211+
[FormHelper](views/helpers/form#rendering-trusted-html) accept trusted HTML in
212+
supported content arguments without requiring `'escape' => false`:
213+
214+
```php
215+
echo $this->Html->link(html('<strong>Read more</strong>'), '/articles');
216+
// <a href="/articles"><strong>Read more</strong></a>
217+
218+
echo $this->Form->button(html('<em>Save</em>'));
219+
// <button type="submit"><em>Save</em></button>
220+
```
221+
222+
Helper methods still return strings. To pass their output as trusted content
223+
to another helper, wrap it with `html()`. Attribute values continue to be
224+
escaped according to the helper's attribute escaping options.
225+
226+
#### Implementing HtmlStringable
227+
228+
Custom components and plugins can implement `Cake\View\HtmlStringable`
229+
instead of returning an `HtmlString`. The interface extends `Stringable` and
230+
requires a `__toString(): string` method that returns trusted HTML:
231+
232+
```php
233+
use Cake\View\HtmlStringable;
234+
235+
final class Badge implements HtmlStringable
236+
{
237+
public function __construct(private string $label)
238+
{
239+
}
240+
241+
public function __toString(): string
242+
{
243+
return '<span class="badge">' . h($this->label) . '</span>';
244+
}
245+
}
246+
247+
echo HtmlString::render(new Badge('News & updates'));
248+
// <span class="badge">News &amp; updates</span>
249+
```
250+
251+
Implementations are responsible for escaping any untrusted values in their
252+
markup. The interface applies to HTML content, and does not bypass attribute
253+
escaping or explicit calls to `h()`.
254+
255+
::: info Added in version 6.0.0
256+
`HtmlString`, `HtmlStringable`, and `Cake\View\html()` were added.
257+
:::
258+
160259
### Setting View Variables
161260

162261
`method` Cake\\View\\View::**set**(array|string $name, mixed $value = null): static

‎docs/en/views/helpers/form.md‎

Lines changed: 66 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,54 @@ re-population and layout. The FormHelper is also flexible - it will do almost
1313
everything for you using conventions, or you can use specific methods to get
1414
only what you need.
1515

16+
## Rendering Trusted HTML
17+
18+
FormHelper accepts [HtmlString](../../views#rendering-trusted-html) and other
19+
`Cake\View\HtmlStringable` values in the following content positions:
20+
21+
- Captions for `button()` and `postButton()`, and content for `postLink()` and
22+
`deleteLink()`.
23+
- Label text for `label()`, the `label` option of `control()`, and the `text`
24+
key of a label options array.
25+
- Option labels for `radio()` and `multiCheckbox()`.
26+
- Explicit error messages passed to `error()` or the `error` option of
27+
`control()`, including individual messages in an array of overrides.
28+
29+
These values render without escaping their markup, while ordinary strings
30+
continue to follow the existing escaping options:
31+
32+
```php
33+
use function Cake\View\html;
34+
35+
echo $this->Form->button(html('<strong>Save</strong>'));
36+
37+
echo $this->Form->control('name', [
38+
'label' => html('<strong>Your name</strong>'),
39+
]);
40+
41+
echo $this->Form->radio('priority', [
42+
['value' => 'high', 'text' => html('<strong>High</strong>')],
43+
['value' => 'normal', 'text' => 'Normal'],
44+
]);
45+
46+
// Override one message while retaining other validation messages.
47+
echo $this->Form->error('name', [
48+
'_empty' => html('<strong>Please enter your name.</strong>'),
49+
]);
50+
```
51+
52+
Only explicit error overrides are treated as trusted HTML. Messages obtained
53+
from the form context, including fallback messages without an override, remain
54+
escaped by default even if they implement `HtmlStringable`.
55+
56+
Wrapping a value does not bypass escaping in attributes, input values,
57+
textarea contents, or select option text. Only wrap markup you control;
58+
`HtmlString` does not sanitize HTML.
59+
60+
::: info Added in version 6.0.0
61+
Support for `HtmlStringable` content was added.
62+
:::
63+
1664
## Starting a Form
1765

1866
`method` Cake\\View\\Helper\\FormHelper::**create**(mixed $context = null, array $options = []): string
@@ -1833,10 +1881,10 @@ If it was 2009, you would get the following:
18331881

18341882
## Creating Labels
18351883

1836-
`method` Cake\\View\\Helper\\FormHelper::**label**(string $fieldName, string $text, array $options): string
1884+
`method` Cake\\View\\Helper\\FormHelper::**label**(string $fieldName, HtmlStringable|string|null $text = null, array $options = []): string
18371885

18381886
- `$fieldName` - A field name in the form `'Modelname.fieldname'`.
1839-
- `$text` - An optional string providing the label caption text.
1887+
- `$text` - An optional string or `HtmlStringable` value providing the label caption.
18401888
- `$options` - Optional. Array containing any of the
18411889
[General Control Options](#general-control-options) as well as any valid HTML attributes.
18421890

@@ -1882,7 +1930,7 @@ field errors and when necessary display customized error messages.
18821930
`method` Cake\\View\\Helper\\FormHelper::**error**(string $fieldName, mixed $text, array $options): string
18831931

18841932
- `$fieldName` - A field name in the form `'Modelname.fieldname'`.
1885-
- `$text` - Optional. A string or array providing the error message(s). If an
1933+
- `$text` - Optional. A string, `HtmlStringable` value, or array providing the error message(s). If an
18861934
array, then it should be a hash of key names => messages. Defaults to
18871935
`null`.
18881936
- `$options` - An optional array that can only contain a boolean with the key
@@ -2053,15 +2101,15 @@ more complex button content you should use `button()`.
20532101

20542102
### Creating Button Elements
20552103

2056-
`method` Cake\\View\\Helper\\FormHelper::**button**(string $title, array $options = []): string
2104+
`method` Cake\\View\\Helper\\FormHelper::**button**(HtmlStringable|string $content, array $options = []): string
20572105

2058-
- `$title` - Mandatory string providing the button's text caption.
2106+
- `$content` - Mandatory string or `HtmlStringable` value providing the button's caption.
20592107
- `$options` - An optional array including any of the
20602108
[General Control Options](#general-control-options), or of the specific button options (see below)
20612109
as well as any valid HTML attributes.
20622110

2063-
Creates an HTML button with the specified title and a default type
2064-
of `'button'`.
2111+
Creates an HTML button with the specified content and a default type
2112+
of `'submit'`.
20652113

20662114
**Options for Button**
20672115

@@ -2072,9 +2120,9 @@ of `'button'`.
20722120
as `submit()` does. This is the default type.
20732121
2. `'reset'` - Creates a form reset button.
20742122
3. `'button'` - Creates a standard push button.
2075-
- `escapeTitle` - Boolean. If set to `true` it will HTML encode
2076-
the value provided inside `$title`. Defaults to `true`.
20772123
- `escape` - Boolean. If set to `true` it will HTML encode
2124+
ordinary strings provided inside `$content`. Defaults to `true`.
2125+
- `escapeAttributes` - Boolean. If set to `true` it will HTML encode
20782126
all the HTML attributes generated for the button. Defaults to `true`.
20792127
- `confirm` - The confirmation message to display on click. Defaults to
20802128
`null`.
@@ -2097,13 +2145,13 @@ Will output:
20972145
<button type="submit">Submit Form</button>
20982146
```
20992147

2100-
Example use of the `'escapeTitle'` option:
2148+
Example use of the `'escape'` option:
21012149

21022150
```php
21032151
// Will render unescaped HTML.
21042152
echo $this->Form->button('<em>Submit Form</em>', [
21052153
'type' => 'submit',
2106-
'escapeTitle' => false,
2154+
'escape' => false,
21072155
]);
21082156
```
21092157

@@ -2165,10 +2213,10 @@ template option on `FormHelper`.
21652213

21662214
### Creating POST Buttons
21672215

2168-
`method` Cake\\View\\Helper\\FormHelper::**postButton**(string $title, mixed $url, array $options = []): string
2216+
`method` Cake\\View\\Helper\\FormHelper::**postButton**(HtmlStringable|string $content, array|string $url, array $options = []): string
21692217

2170-
- `$title` - Mandatory string providing the button's text caption. By default
2171-
not HTML encoded.
2218+
- `$content` - Mandatory string or `HtmlStringable` value providing the button's
2219+
caption. Ordinary strings are HTML encoded by default.
21722220
- `$url` - The URL of the form provided as a string or as array.
21732221
- `$options` - An optional array including any of the
21742222
[General Control Options](#general-control-options), or of the specific options (see below) as well
@@ -2218,9 +2266,9 @@ inside opened forms.
22182266

22192267
### Creating POST Links
22202268

2221-
`method` Cake\\View\\Helper\\FormHelper::**postLink**(string $title, array|string|null $url = null, array $options = []): string
2269+
`method` Cake\\View\\Helper\\FormHelper::**postLink**(HtmlStringable|string $content, array|string|null $url = null, array $options = []): string
22222270

2223-
- `$title` - Mandatory string providing the text to be wrapped in `<a>`
2271+
- `$content` - Mandatory string or `HtmlStringable` value to be wrapped in `<a>`
22242272
tags.
22252273
- `$url` - Optional. String or array which contains the URL
22262274
of the form (Cake-relative or external URL starting with `http://`).
@@ -2269,9 +2317,9 @@ use `Cake\View\Helper\FormHelper::button()` or
22692317

22702318
### Creating DELETE Links
22712319

2272-
`method` Cake\\View\\Helper\\FormHelper::**deleteLink**(string $title, array|string|null $url = null, array $options = []): string
2320+
`method` Cake\\View\\Helper\\FormHelper::**deleteLink**(HtmlStringable|string $content, array|string|null $url = null, array $options = []): string
22732321

2274-
- `$title` - Mandatory string providing the text to be wrapped in `<a>`
2322+
- `$content` - Mandatory string or `HtmlStringable` value to be wrapped in `<a>`
22752323
tags.
22762324
- `$url` - Optional. String or array which contains the URL
22772325
of the form (Cake-relative or external URL starting with `http://`).

0 commit comments

Comments
 (0)