Skip to content

Commit

Permalink
JSONEncoder - cast nil template to empty string
Browse files Browse the repository at this point in the history
  • Loading branch information
leandrocp committed Nov 10, 2023
1 parent 4fa1eca commit 62ca059
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/beacon/template/heex/json_encoder.ex
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,13 @@ defmodule Beacon.Template.HEEx.JSONEncoder do
"""
@spec encode(Beacon.Types.Site.t(), String.t(), map()) :: {:ok, [token()]} | {:error, String.t()}
def encode(site, template, assigns \\ %{}) when is_atom(site) and is_binary(template) and is_map(assigns) do
def encode(site, template, assigns \\ %{})

def encode(site, nil = _template, assigns) when is_atom(site) and is_map(assigns) do
encode(site, "", assigns)
end

def encode(site, template, assigns) when is_atom(site) and is_binary(template) and is_map(assigns) do
case Beacon.Template.HEEx.Tokenizer.tokenize(template) do
{:ok, tokens} -> {:ok, encode_tokens(tokens, site, assigns)}
error -> error
Expand Down
4 changes: 4 additions & 0 deletions test/beacon/template/heex/json_encoder_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ defmodule Beacon.Template.HEEx.JSONEncoderTest do
assert encoded == expected
end

test "nil template cast to empty string" do
assert_output(nil, [])
end

test "html elements with attrs" do
assert_output(~S|<div>content</div>|, [%{"attrs" => %{}, "content" => ["content"], "tag" => "div"}])
assert_output(~S|<a href="/contact">contact</a>|, [%{"attrs" => %{"href" => "/contact"}, "content" => ["contact"], "tag" => "a"}])
Expand Down

0 comments on commit 62ca059

Please sign in to comment.