From 3915a656248682905d9a1b889aae7a3a65f61288 Mon Sep 17 00:00:00 2001 From: Mitchell Hanberg Date: Sun, 20 Oct 2024 19:15:39 -0400 Subject: [PATCH] fix: allow normal list elements in class attr 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 --- lib/temple/ast/utils.ex | 10 +++++++++- test/temple/ast/utils_test.exs | 27 --------------------------- test/temple/renderer_test.exs | 14 +++++++++++--- 3 files changed, 20 insertions(+), 31 deletions(-) diff --git a/lib/temple/ast/utils.ex b/lib/temple/ast/utils.ex index dbb7c1b..c07b266 100644 --- a/lib/temple/ast/utils.ex +++ b/lib/temple/ast/utils.ex @@ -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'"'}] diff --git a/test/temple/ast/utils_test.exs b/test/temple/ast/utils_test.exs index 4e0370e..86cc1e0 100644 --- a/test/temple/ast/utils_test.exs +++ b/test/temple/ast/utils_test.exs @@ -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 diff --git a/test/temple/renderer_test.exs b/test/temple/renderer_test.exs index 7ae5c66..5e9b7a3 100644 --- a/test/temple/renderer_test.exs +++ b/test/temple/renderer_test.exs @@ -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 = """ -
+
hello world
+
+ hi +
+ """ assert_html expected, result