Skip to content

Commit

Permalink
Make sure class={@value} in HEEx is escaped
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed Sep 23, 2021
1 parent b7cf6da commit 62a0139
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
21 changes: 11 additions & 10 deletions lib/phoenix_html/tag.ex
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,15 @@ defmodule Phoenix.HTML.Tag do
{:safe, attrs |> Enum.to_list() |> build_attrs()}
end

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([{"data", v} | t]) when is_list(v),
do: nested_attrs(v, " data", t)

Expand All @@ -145,15 +154,6 @@ defmodule Phoenix.HTML.Tag do
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)]

Expand All @@ -172,10 +172,11 @@ defmodule Phoenix.HTML.Tag do
value
|> Enum.filter(& &1)
|> Enum.join(" ")
|> attr_escape()
end

defp class_value(value) do
value
attr_escape(value)
end

defp key_escape(value) when is_atom(value), do: String.replace(Atom.to_string(value), "_", "-")
Expand Down
11 changes: 9 additions & 2 deletions test/phoenix_html/tag_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,18 @@ defmodule Phoenix.HTML.TagTest do

test "handle class value as string" do
assert attributes_escape([{:class, "btn"}]) |> safe_to_string() == ~s( class="btn")
assert attributes_escape([{:class, "<active>"}]) |> safe_to_string() == ~s( class="&lt;active&gt;")
end

test "handle class value as list" do
assert attributes_escape([{:class, ["btn", nil, false, "active"]}]) |> safe_to_string() ==
~s( class="btn active")
assert attributes_escape([{:class, ["btn", nil, false, "<active>"]}]) |> safe_to_string() ==
~s( class="btn &lt;active&gt;")
end

test "handle class value as false/nil/true" do
assert attributes_escape([{:class, false}]) |> safe_to_string() == ~s()
assert attributes_escape([{:class, nil}]) |> safe_to_string() == ~s()
assert attributes_escape([{:class, true}]) |> safe_to_string() == ~s( class)
end

test "handle class key as string" do
Expand Down

0 comments on commit 62a0139

Please sign in to comment.