Skip to content

Commit

Permalink
fix: allow normal list elements in class attr
Browse files Browse the repository at this point in the history
This allows you to include strings in class lists instead of only
allowing keyword lists.

So `["foo", "bar", nil, "baz": true]` will result in `"foo bar baz"` now

Fixes #238
  • Loading branch information
mhanberg committed Oct 20, 2024
1 parent a18e6fe commit 3915a65
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 31 deletions.
10 changes: 9 additions & 1 deletion lib/temple/ast/utils.ex
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,15 @@ defmodule Temple.Ast.Utils do
def build_attr("class", classes) when is_list(classes) do
value =
quote do
String.trim_leading(for {class, true} <- unquote(classes), into: "", do: " #{class}")
String.trim_leading(
for value <- unquote(classes), into: "" do
case value do
{class, true} -> " #{class}"
class when is_binary(class) -> " #{class}"
_ -> ""
end
end
)
end

[{:text, ~s' class="'}, {:expr, value}, {:text, ~s'"'}]
Expand Down
27 changes: 0 additions & 27 deletions test/temple/ast/utils_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -30,33 +30,6 @@ defmodule Temple.Ast.UtilsTest do
) == Macro.to_string(actual)
end

test "returns a list of text and expr nodes for the class object syntax" do
class_ast = quote(do: @class)

list =
quote do
["text-red": unquote(class_ast)]
end

expr =
quote do
String.trim_leading(for {class, true} <- unquote(list), into: "", do: " #{class}")
end

attrs = [class: ["text-red": class_ast]]

actual = Utils.compile_attrs(attrs)

assert [
{:text, ~s' class="'},
{:expr, result_expr},
{:text, ~s'"'}
] = actual

# the ast metadata is different, let's just compare stringified versions
assert Macro.to_string(result_expr) == Macro.to_string(expr)
end

test "the rest! attribute will mix in the values at runtime" do
rest_ast =
quote do
Expand Down
14 changes: 11 additions & 3 deletions test/temple/renderer_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -485,20 +485,28 @@ defmodule Temple.RendererTest do
end

describe "special attribute stuff" do
test "class object syntax" do
test "class list " do
result =
Renderer.compile do
div class: ["hello world": false, "text-red": true] do
div class: ["foo bar", "hello world": false, "text-red": true] do
"hello world"
end

div class: ["foo", nil, "bar"] do
"hi"
end
end

# html
expected = """
<div class="text-red">
<div class="foo bar text-red">
hello world
</div>
<div class="foo bar">
hi
</div>
"""

assert_html expected, result
Expand Down

0 comments on commit 3915a65

Please sign in to comment.