Allow passing content as first arg instead of block

This commit is contained in:
Mitchell Hanberg 2019-04-27 11:46:02 -04:00
parent 53ede43000
commit d6ed780949
2 changed files with 41 additions and 5 deletions

View file

@ -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

View file

@ -130,6 +130,16 @@ defmodule Dsl.HtmlTest do
assert result == ~s{<div class="hello" id="12"></div>}
end
test "can accept content as the first argument" do
{:safe, result} =
htm do
div("CONTENT")
div("MORE", class: "hi")
end
assert result == ~s{<div>CONTENT</div><div class="hi">MORE</div>}
end
end
describe "void elements" do
@ -156,7 +166,7 @@ defmodule Dsl.HtmlTest do
test "text is excaped" do
{:safe, result} =
htm do
text "<div>Text</div>"
text("<div>Text</div>")
end
assert result == ~s{&lt;div&gt;Text&lt;/div&gt;}