/
tag.ex
388 lines (285 loc) · 11.2 KB
/
tag.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
defmodule Phoenix.HTML.Tag do
@moduledoc ~S"""
Helpers related to producing HTML tags within templates.
> Note: the examples in this module use `safe_to_string/1`
> imported from `Phoenix.HTML` for readability.
> Note: with the addition of the HEEx template engine to
> Phoenix applications, the functions in this module have
> lost a bit of relevance. Whenever possible, prefer to use
> the HEEx template engine instead of the functions here.
> For example, instead of:
>
> <%= content_tag :div, class: @class do %>
> Hello
> <% end %>
>
> Do:
>
> <div class={@class}>
> Hello
> </div>
"""
import Phoenix.HTML
@csrf_param "_csrf_token"
@doc ~S"""
Creates an HTML tag with the given name and options.
iex> safe_to_string tag(:br)
"<br>"
iex> safe_to_string tag(:input, type: "text", name: "user_id")
"<input name=\"user_id\" type=\"text\">"
## Data attributes
In order to add custom data attributes you need to pass
a tuple containing :data atom and a keyword list
with data attributes' names and values as the first element
in the tag's attributes keyword list:
iex> safe_to_string tag(:input, [data: [foo: "bar"], id: "some_id"])
"<input data-foo=\"bar\" id=\"some_id\">"
## Boolean values
In case an attribute contains a boolean value, its key
is repeated when it is true, as expected in HTML, or
the attribute is completely removed if it is false:
iex> safe_to_string tag(:audio, autoplay: "autoplay")
"<audio autoplay=\"autoplay\">"
iex> safe_to_string tag(:audio, autoplay: true)
"<audio autoplay>"
iex> safe_to_string tag(:audio, autoplay: false)
"<audio>"
If you want the boolean attribute to be sent as is,
you can explicitly convert it to a string before.
"""
def tag(name), do: tag(name, [])
def tag(name, attrs) when is_list(attrs) do
{:safe, [?<, to_string(name), sorted_attrs(attrs), ?>]}
end
@doc ~S"""
Creates an HTML tag with given name, content, and attributes.
See `Phoenix.HTML.Tag.tag/2` for more information and examples.
iex> safe_to_string content_tag(:p, "Hello")
"<p>Hello</p>"
iex> safe_to_string content_tag(:p, "<Hello>", class: "test")
"<p class=\"test\"><Hello></p>"
iex> safe_to_string(content_tag :p, class: "test" do
...> "Hello"
...> end)
"<p class=\"test\">Hello</p>"
iex> safe_to_string content_tag(:option, "Display Value", [{:data, [foo: "bar"]}, value: "value"])
"<option data-foo=\"bar\" value=\"value\">Display Value</option>"
"""
def content_tag(name, do: block) do
content_tag(name, block, [])
end
def content_tag(name, content) do
content_tag(name, content, [])
end
def content_tag(name, attrs, do: block) when is_list(attrs) do
content_tag(name, block, attrs)
end
def content_tag(name, content, attrs) when is_list(attrs) do
name = to_string(name)
{:safe, escaped} = html_escape(content)
{:safe, [?<, name, sorted_attrs(attrs), ?>, escaped, ?<, ?/, name, ?>]}
end
@doc ~S"""
Escapes an enumerable of attributes, returning iodata.
Pay attention that, unlike `tag/2` and `content_tag/2`, this
function does not sort the attributes. However if given a map,
note also that the key ordering may change.
iex> safe_to_string attributes_escape(title: "the title", id: "the id", selected: true)
" title=\"the title\" id=\"the id\" selected"
iex> safe_to_string attributes_escape(%{data: [phx: [value: [foo: "bar"]]], class: "foo"})
" class=\"foo\" data-phx-value-foo=\"bar\""
"""
def attributes_escape(attrs) when is_list(attrs) do
{:safe, build_attrs(attrs)}
end
def attributes_escape(attrs) do
{:safe, attrs |> Enum.to_list() |> build_attrs()}
end
defp build_attrs([{"data", v} | t]) when is_list(v),
do: nested_attrs(v, " data", t)
defp build_attrs([{"aria", v} | t]) when is_list(v),
do: nested_attrs(v, " aria", t)
defp build_attrs([{"class", v} | t]) when is_list(v),
do: [" class=\"", class_value(v), ?" | build_attrs(t)]
defp build_attrs([{:data, v} | t]) when is_list(v),
do: nested_attrs(v, " data", t)
defp build_attrs([{:aria, v} | t]) when is_list(v),
do: nested_attrs(v, " aria", t)
defp build_attrs([{:class, v} | t]) when is_list(v),
do: [" class=\"", class_value(v), ?" | build_attrs(t)]
defp build_attrs([{k, true} | t]),
do: [?\s, key_escape(k) | build_attrs(t)]
defp build_attrs([{_, false} | t]),
do: build_attrs(t)
defp build_attrs([{_, nil} | t]),
do: build_attrs(t)
defp build_attrs([{k, v} | t]),
do: [?\s, key_escape(k), ?=, ?", attr_escape(v), ?" | build_attrs(t)]
defp build_attrs([]), do: []
defp nested_attrs([{k, v} | kv], attr, t) when is_list(v),
do: [nested_attrs(v, "#{attr}-#{key_escape(k)}", []) | nested_attrs(kv, attr, t)]
defp nested_attrs([{k, v} | kv], attr, t),
do: [attr, ?-, key_escape(k), ?=, ?", attr_escape(v), ?" | nested_attrs(kv, attr, t)]
defp nested_attrs([], _attr, t),
do: build_attrs(t)
defp class_value(value) when is_list(value) do
value
|> Enum.filter(& &1)
|> Enum.join(" ")
end
defp class_value(value) do
value
end
defp key_escape(value) when is_atom(value), do: String.replace(Atom.to_string(value), "_", "-")
defp key_escape(value), do: attr_escape(value)
defp attr_escape({:safe, data}), do: data
defp attr_escape(nil), do: []
defp attr_escape(other) when is_binary(other), do: Phoenix.HTML.Engine.encode_to_iodata!(other)
defp attr_escape(other), do: Phoenix.HTML.Safe.to_iodata(other)
defp sorted_attrs(attrs) when is_list(attrs),
do: attrs |> normalize_attrs() |> Enum.sort() |> build_attrs()
defp sorted_attrs(attrs),
do: attrs |> Enum.to_list() |> sorted_attrs()
defp normalize_attrs([{k, v} | tail]), do: [{k, v} | normalize_attrs(tail)]
defp normalize_attrs([k | tail]), do: [{k, true} | normalize_attrs(tail)]
defp normalize_attrs([]), do: []
@doc ~S"""
Generates a form tag.
This function generates the `<form>` tag without its closing part.
Check `form_tag/3` for generating an enclosing tag.
## Examples
form_tag("/hello")
<form action="/hello" method="post">
form_tag("/hello", method: :get)
<form action="/hello" method="get">
## Options
* `:method` - the HTTP method. If the method is not "get" nor "post",
an input tag with name `_method` is generated along-side the form tag.
Defaults to "post".
* `:multipart` - when true, sets enctype to "multipart/form-data".
Required when uploading files
* `:csrf_token` - for "post" requests, the form tag will automatically
include an input tag with name `_csrf_token`. When set to false, this
is disabled
All other options are passed to the underlying HTML tag.
## CSRF Protection
By default, CSRF tokens are generated through `Plug.CSRFProtection`.
"""
def form_tag(action, opts \\ [])
def form_tag(action, do: block) do
form_tag(action, [], do: block)
end
def form_tag(action, opts) when is_list(opts) do
{:safe, method} = html_escape(Keyword.get(opts, :method, "post"))
{extra, opts} =
case method do
"get" ->
{"", opts}
"post" ->
{csrf, opts} = csrf_form_tag(action, opts)
{csrf, Keyword.put(opts, :method, "post")}
_ ->
{csrf, opts} = csrf_form_tag(action, opts)
{[~s'<input name="_method" type="hidden" value="', to_string(method), ~s'">' | csrf],
Keyword.put(opts, :method, "post")}
end
opts =
case Keyword.pop(opts, :multipart, false) do
{false, opts} -> opts
{true, opts} -> Keyword.put(opts, :enctype, "multipart/form-data")
end
html_escape([tag(:form, [action: action] ++ opts), raw(extra)])
end
@doc """
Generates a form tag with the given contents.
## Examples
form_tag("/hello", method: "get") do
"Hello"
end
<form action="/hello" method="get">...Hello...</form>
"""
def form_tag(action, options, do: block) do
html_escape([form_tag(action, options), block, raw("</form>")])
end
defp csrf_form_tag(to, opts) do
case Keyword.pop(opts, :csrf_token, true) do
{csrf_token, opts} when is_binary(csrf_token) ->
{[~s'<input name="#{@csrf_param}" type="hidden" value="', csrf_token, ~s'">'], opts}
{true, opts} ->
csrf_token = csrf_token_value(to)
{[~s'<input name="#{@csrf_param}" type="hidden" value="', csrf_token, ~s'">'], opts}
{false, opts} ->
{[], opts}
end
end
@doc """
Returns the `csrf_token` value to be used by forms, meta tags, etc.
By default, CSRF tokens are generated through `Plug.CSRFProtection`
which is capable of generating a separate token per host. Therefore
it is recommended to pass the `URI` of the destination as argument.
If none is given `%URI{host: nil}` is used, which implies a local
request is being done.
"""
def csrf_token_value(to \\ %URI{host: nil}) do
{mod, fun, args} = Application.fetch_env!(:phoenix_html, :csrf_token_reader)
apply(mod, fun, [to | args])
end
@doc """
Generates a meta tag with CSRF information.
Additional options to the tag can be given.
"""
def csrf_meta_tag(opts \\ []) do
tag(:meta, [name: "csrf-token", content: csrf_token_value()] ++ opts)
end
@doc """
Generates a hidden input tag with a CSRF token.
This could be used when writing a form without the use of tag
helpers like `form_tag/3` or `form_for/4`, while maintaining
CSRF protection.
The `to` argument should be the same as the form action.
## Example
<form action="/login" method="POST">
<%= csrf_input_tag("/login") %>
etc.
</form>
Additional options to the tag can be given.
"""
def csrf_input_tag(to, opts \\ []) do
csrf_token = csrf_token_value(to)
tag(:input, [type: "hidden", name: @csrf_param, value: csrf_token] ++ opts)
end
@doc """
Generates an img tag with a src.
## Examples
img_tag(user.photo_path)
<img src="/photo.png">
img_tag(user.photo, class: "image")
<img src="/smile.png" class="image">
To generate a path to an image hosted in your application "priv/static",
with the `@conn` endpoint, use `static_path/2` to get a URL with
cache control parameters:
img_tag(Routes.static_path(@conn, "/logo.png"))
<img src="/logo-123456.png?vsn=d">
For responsive images, pass a map, list or string through `:srcset`.
img_tag("/logo.png", srcset: %{"/logo.png" => "1x", "/logo-2x.png" => "2x"})
<img src="/logo.png" srcset="/logo.png 1x, /logo-2x.png 2x">
img_tag("/logo.png", srcset: ["/logo.png", {"/logo-2x.png", "2x"}])
<img src="/logo.png" srcset="/logo.png, /logo-2x.png 2x">
"""
def img_tag(src, opts \\ []) do
opts =
case Keyword.pop(opts, :srcset) do
{nil, opts} -> opts
{srcset, opts} -> [srcset: stringify_srcset(srcset)] ++ opts
end
tag(:img, Keyword.put_new(opts, :src, src))
end
defp stringify_srcset(srcset) when is_map(srcset) or is_list(srcset) do
Enum.map_join(srcset, ", ", fn
{src, descriptor} -> "#{src} #{descriptor}"
default -> default
end)
end
defp stringify_srcset(srcset) when is_binary(srcset),
do: srcset
end