/
safe.ex
73 lines (58 loc) · 1.76 KB
/
safe.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
defprotocol Phoenix.HTML.Safe do
@moduledoc """
Defines the HTML safe protocol.
In order to promote HTML safety, Phoenix templates
do not use `Kernel.to_string/1` to convert data types to
strings in templates. Instead, Phoenix uses this
protocol which must be implemented by data structures
and guarantee that a HTML safe representation is returned.
Furthermore, this protocol relies on iodata, which provides
better performance when sending or streaming data to the client.
"""
def to_iodata(data)
end
defimpl Phoenix.HTML.Safe, for: Atom do
def to_iodata(nil), do: ""
def to_iodata(atom), do: Plug.HTML.html_escape(Atom.to_string(atom))
end
defimpl Phoenix.HTML.Safe, for: BitString do
defdelegate to_iodata(data), to: Plug.HTML, as: :html_escape
end
defimpl Phoenix.HTML.Safe, for: List do
def to_iodata([h|t]) do
[to_iodata(h)|to_iodata(t)]
end
def to_iodata([]) do
[]
end
def to_iodata(?<), do: "<"
def to_iodata(?>), do: ">"
def to_iodata(?&), do: "&"
def to_iodata(?"), do: """
def to_iodata(?'), do: "'"
def to_iodata(h) when is_integer(h) do
h
end
def to_iodata(h) when is_binary(h) do
Plug.HTML.html_escape(h)
end
def to_iodata({:safe, data}) do
data
end
def to_iodata(other) do
raise ArgumentError,
"lists in Phoenix.HTML and templates may only contain integers, binaries or other lists, " <>
"got invalid entry: #{inspect other}"
end
end
defimpl Phoenix.HTML.Safe, for: Integer do
def to_iodata(data), do: Integer.to_string(data)
end
defimpl Phoenix.HTML.Safe, for: Float do
def to_iodata(data) do
IO.iodata_to_binary(:io_lib_format.fwrite_g(data))
end
end
defimpl Phoenix.HTML.Safe, for: Tuple do
def to_iodata({:safe, data}), do: data
end