Packages
raxx
0.15.11
1.1.0
1.0.1
1.0.0
1.0.0-rc.3
1.0.0-rc.2
retired
1.0.0-rc.1
retired
1.0.0-rc.0
retired
0.18.1
0.18.0
0.17.6
0.17.5
0.17.4
0.17.3
0.17.2
0.17.1
0.17.0
0.16.1
0.16.0
retired
0.15.11
0.15.10
0.15.9
0.15.8
0.15.7
0.15.6
0.15.5
0.15.4
0.15.3
0.15.2
0.15.1
0.15.0
0.14.14
0.14.13
0.14.12
0.14.11
0.14.10
0.14.9
0.14.8
0.14.7
0.14.6
0.14.5
0.14.4
0.14.3
0.14.2
0.14.1
0.14.0
0.13.0
0.12.3
0.12.2
0.12.1
0.12.0
0.11.1
0.11.0
0.10.5
0.10.4
0.10.3
0.10.2
0.10.1
0.10.0
0.9.0
0.8.2
0.8.1
0.8.0
0.7.1
0.7.0
0.6.0
0.5.2
0.5.1
0.5.0
0.4.3
0.4.2
0.4.1
0.4.0
0.3.0
0.2.0
0.1.0
0.0.1
Interface for HTTP webservers, frameworks and clients.
Current section
Files
Jump to
Current section
Files
lib/eex/html.ex
defmodule EEx.HTML do
@moduledoc """
Conveniences for generating HTML.
"""
alias __MODULE__.Safe
@doc """
Escape the HTML content derived from the given term.
The content is returned wrapped in an `EEx.HTML.Safe` struct so it is not reescaped by templates etc.
"""
# Short circuit escaping the content, if already wrapped as safe.
def escape(content = %Safe{}) do
content
end
def escape(term) do
data = Safe.to_iodata(term)
raw(data)
end
def raw(content = %Safe{}) do
content
end
def raw(iodata) do
%Safe{data: iodata}
end
@doc ~S"""
Escapes the given HTML to string.
iex> EEx.HTML.escape_to_binary("foo")
"foo"
iex> EEx.HTML.escape_to_binary("<foo>")
"<foo>"
iex> EEx.HTML.escape_to_binary("quotes: \" & \'")
"quotes: " & '"
"""
@spec escape_to_binary(String.t()) :: String.t()
def escape_to_binary(data) when is_binary(data) do
IO.iodata_to_binary(to_iodata(data, 0, data, []))
end
@doc ~S"""
Escapes the given HTML to iodata.
iex> EEx.HTML.escape_to_iodata("foo")
"foo"
iex> EEx.HTML.escape_to_iodata("<foo>")
[[[] | "<"], "foo" | ">"]
iex> EEx.HTML.escape_to_iodata("quotes: \" & \'")
[[[[], "quotes: " | """], " " | "&"], " " | "'"]
"""
@spec escape_to_iodata(String.t()) :: iodata
def escape_to_iodata(data) when is_binary(data) do
to_iodata(data, 0, data, [])
end
escapes = [
{?<, "<"},
{?>, ">"},
{?&, "&"},
{?", """},
{?', "'"}
]
for {match, insert} <- escapes do
defp to_iodata(<<unquote(match), rest::bits>>, skip, original, acc) do
to_iodata(rest, skip + 1, original, [acc | unquote(insert)])
end
end
defp to_iodata(<<_char, rest::bits>>, skip, original, acc) do
to_iodata(rest, skip, original, acc, 1)
end
defp to_iodata(<<>>, _skip, _original, acc) do
acc
end
for {match, insert} <- escapes do
defp to_iodata(<<unquote(match), rest::bits>>, skip, original, acc, len) do
part = binary_part(original, skip, len)
to_iodata(rest, skip + len + 1, original, [acc, part | unquote(insert)])
end
end
defp to_iodata(<<_char, rest::bits>>, skip, original, acc, len) do
to_iodata(rest, skip, original, acc, len + 1)
end
defp to_iodata(<<>>, 0, original, _acc, _len) do
original
end
defp to_iodata(<<>>, skip, original, acc, len) do
[acc | binary_part(original, skip, len)]
end
end