diff --git a/lib/dsl/html.ex b/lib/dsl/html.ex index 0c1e0f4..9d20afa 100644 --- a/lib/dsl/html.ex +++ b/lib/dsl/html.ex @@ -41,9 +41,15 @@ defmodule Dsl.Html do end for el <- @nonvoid_elements do - defmacro unquote(el)(attrs \\ []) + defmacro unquote(el)() do + el = unquote(el) - defmacro unquote(el)(attrs) do + quote do + unquote(el)([], nil) + end + end + + defmacro unquote(el)(attrs) when is_list(attrs) do el = unquote(el) {inner, attrs} = Keyword.pop(attrs, :do, nil) @@ -52,7 +58,24 @@ defmodule Dsl.Html do end end - defmacro unquote(el)(attrs, inner) do + defmacro unquote(el)(content) when is_binary(content) do + el = unquote(el) + + quote do + unquote(el)(unquote(content), []) + end + end + + defmacro unquote(el)(content, attrs) when not is_list(content) and is_list(attrs) do + el = unquote(el) + text = {:text, [], [content]} + + quote do + unquote(el)(unquote(attrs), unquote(text)) + end + end + + defmacro unquote(el)(attrs, inner) when is_list(attrs) do el = unquote(el) quote do @@ -81,7 +104,10 @@ defmodule Dsl.Html do defmacro text(text) do quote do - put_buffer(var!(buff, Dsl.Html), unquote(text) |> to_string |> HTML.html_escape |> HTML.safe_to_string()) + put_buffer( + var!(buff, Dsl.Html), + unquote(text) |> to_string |> HTML.html_escape() |> HTML.safe_to_string() + ) end end diff --git a/test/dsl/html_test.exs b/test/dsl/html_test.exs index e30536a..07b7acf 100644 --- a/test/dsl/html_test.exs +++ b/test/dsl/html_test.exs @@ -130,6 +130,16 @@ defmodule Dsl.HtmlTest do assert result == ~s{
} end + + test "can accept content as the first argument" do + {:safe, result} = + htm do + div("CONTENT") + div("MORE", class: "hi") + end + + assert result == ~s{
CONTENT
MORE
} + end end describe "void elements" do @@ -156,7 +166,7 @@ defmodule Dsl.HtmlTest do test "text is excaped" do {:safe, result} = htm do - text "
Text
" + text("
Text
") end assert result == ~s{<div>Text</div>}