0
# Phoenix.HTML
1
2
Building blocks for working with HTML in Phoenix. Phoenix.HTML provides essential functionality for generating secure, dynamic HTML content in Elixir web applications through three core capabilities: HTML safety mechanisms that prevent XSS attacks, comprehensive form abstractions for data binding and validation, and client-side JavaScript enhancements.
3
4
## Package Information
5
6
- **Package Name**: phoenix_html
7
- **Package Type**: hex
8
- **Language**: Elixir
9
- **Installation**: `{:phoenix_html, "~> 4.2"}`
10
11
## Core Imports
12
13
```elixir
14
# Core HTML safety functions
15
import Phoenix.HTML
16
17
# Form handling
18
import Phoenix.HTML.Form
19
```
20
21
For templates and views:
22
```elixir
23
# Import in your view modules or templates
24
import Phoenix.HTML
25
import Phoenix.HTML.Form
26
```
27
28
## Basic Usage
29
30
```elixir
31
import Phoenix.HTML
32
33
# HTML safety and escaping
34
safe_content = raw("<p>This is safe HTML</p>")
35
escaped = html_escape("<script>alert('XSS')</script>")
36
string_result = safe_to_string(escaped)
37
38
# Attribute escaping for dynamic HTML generation
39
attrs = [class: ["btn", "btn-primary"], data: [confirm: "Are you sure?"]]
40
escaped_attrs = attributes_escape(attrs)
41
42
# Form creation from data structures
43
form_data = %{name: "John", email: "john@example.com"}
44
form = Phoenix.HTML.FormData.to_form(form_data, as: :user)
45
46
# Field access and information
47
field = form[:name]
48
field_id = Phoenix.HTML.Form.input_id(form, :name)
49
field_name = Phoenix.HTML.Form.input_name(form, :name)
50
field_value = Phoenix.HTML.Form.input_value(form, :name)
51
```
52
53
## Architecture
54
55
Phoenix.HTML is built around several key components:
56
57
- **Safety Protocol**: The `Phoenix.HTML.Safe` protocol ensures all data is properly escaped before rendering
58
- **Form Data Protocol**: The `Phoenix.HTML.FormData` protocol converts various data structures to form representations
59
- **Engine Integration**: The `Phoenix.HTML.Engine` integrates with EEx templates for automatic HTML safety
60
- **Client Enhancement**: JavaScript library provides progressive enhancement for forms and links
61
62
This design provides a comprehensive, secure foundation for HTML generation in Phoenix applications while maintaining performance through iodata optimization.
63
64
## Capabilities
65
66
### HTML Safety and Escaping
67
68
Core functions for preventing XSS attacks by properly escaping HTML content, marking safe content, and handling attribute escaping. These functions form the security foundation of Phoenix HTML generation.
69
70
```elixir { .api }
71
@type safe :: {:safe, iodata}
72
@type unsafe :: Phoenix.HTML.Safe.t()
73
74
def raw(iodata | safe | nil) :: safe
75
def html_escape(unsafe) :: safe
76
def safe_to_string(safe) :: String.t()
77
def attributes_escape(attrs) :: safe
78
def javascript_escape(binary | safe) :: binary | safe
79
def css_escape(String.t()) :: String.t()
80
```
81
82
[HTML Safety](./html-safety.md)
83
84
### Form Handling and Data Binding
85
86
Comprehensive form abstractions that convert data structures into form representations, handle field access, validation, and provide utilities for form rendering and data binding.
87
88
```elixir { .api }
89
defmodule Phoenix.HTML.Form do
90
@type t :: %Phoenix.HTML.Form{
91
source: Phoenix.HTML.FormData.t(),
92
name: String.t(),
93
data: %{field => term},
94
action: atom(),
95
params: %{binary => term}
96
}
97
@type field :: atom | String.t()
98
end
99
100
def input_value(t | atom, field) :: term
101
def input_id(t | atom, field) :: String.t()
102
def input_id(t | atom, field, value) :: String.t()
103
def input_name(t | atom, field) :: String.t()
104
def input_validations(t, field) :: Keyword.t()
105
def input_changed?(t, t, field) :: boolean()
106
def normalize_value(String.t(), term) :: term
107
def options_for_select(options, selected_values) :: safe
108
def fetch(t, field) :: {:ok, Phoenix.HTML.FormField.t()} | :error
109
```
110
111
[Forms and Data Binding](./forms.md)
112
113
### JavaScript Integration
114
115
Client-side enhancements through a lightweight JavaScript library that provides confirmation dialogs, HTTP method support for links, and custom event handling for progressive enhancement.
116
117
```javascript { .api }
118
// Automatic handling of data attributes:
119
// data-confirm="message" - Shows confirmation dialog
120
// data-method="patch|post|put|delete" - Sends HTTP request
121
// data-to="url" - Target URL for method requests
122
// data-csrf="token" - CSRF token inclusion
123
124
// Custom event for integration:
125
window.addEventListener('phoenix.link.click', function(e) {
126
// Custom behavior before default handling
127
});
128
```
129
130
[JavaScript Enhancement](./javascript.md)
131
132
## Types
133
134
```elixir { .api }
135
# HTML Safety Types
136
@type Phoenix.HTML.safe :: {:safe, iodata}
137
@type Phoenix.HTML.unsafe :: Phoenix.HTML.Safe.t()
138
139
# Form Types
140
defmodule Phoenix.HTML.Form do
141
@type t :: %__MODULE__{
142
source: Phoenix.HTML.FormData.t(),
143
impl: module,
144
id: String.t(),
145
name: String.t(),
146
data: %{field => term},
147
action: atom(),
148
hidden: Keyword.t(),
149
params: %{binary => term},
150
errors: [{field, term}],
151
options: Keyword.t(),
152
index: nil | non_neg_integer
153
}
154
155
@type field :: atom | String.t()
156
end
157
158
defmodule Phoenix.HTML.FormField do
159
@type t :: %__MODULE__{
160
id: String.t(),
161
name: String.t(),
162
errors: [term],
163
field: Phoenix.HTML.Form.field(),
164
form: Phoenix.HTML.Form.t(),
165
value: term
166
}
167
end
168
169
# Protocol Types
170
defprotocol Phoenix.HTML.FormData do
171
@type t :: term # Any data structure implementing this protocol
172
end
173
174
defprotocol Phoenix.HTML.Safe do
175
@type t :: term # Any data structure that can be converted to safe HTML
176
end
177
```
178
179
## Error Handling
180
181
Phoenix.HTML handles errors gracefully with informative messages:
182
183
- **Missing Assigns**: `fetch_assign!/2` provides clear error messages for undefined template variables
184
- **Invalid Field Access**: Form field access validates field types (atom or string)
185
- **Protocol Errors**: Safe protocol implementations handle unsupported data types appropriately
186
- **JavaScript Errors**: Client-side code includes IE<=9 compatibility and graceful degradation