Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handling nil/false attributes and attr defaults consistently #3602

Open
thiagomajesk opened this issue Dec 26, 2024 · 0 comments
Open

Handling nil/false attributes and attr defaults consistently #3602

thiagomajesk opened this issue Dec 26, 2024 · 0 comments

Comments

@thiagomajesk
Copy link
Contributor

thiagomajesk commented Dec 26, 2024

Typically nil and false will omit the attribute as per the documentation:
https://hexdocs.pm/phoenix_live_view/Phoenix.Component.html#sigil_H/2-syntax

false or nil - if a value is false or nil, the attribute is omitted. Some attributes may be rendered with an empty value, for optimization purposes, if it has the same effect as omitting [...]

So, the following:

<span class={nil}>Hello World</span>
<span class={false}>Hello World</span>

Will output: <span class="">Hello World</span>

And the following:

<span data-class={nil}>Hello World</span>
<span data-class={false}>Hello World</span>

Will output: <span>Hello World</span>

It gets especially weird because this is not how it's handled if you have a function component with global attributes:

attr :rest, :global
slot :inner_block

defp span(assigns), do: ~H"<span {@rest}>{render_slot(@inner_block)}</span>"

The following:

<.span class={nil}>Hello World</.span>
<.span class={false}>Hello World</.span>
<.span data-class={nil}>Hello World</.span>
<.span data-class={false}>Hello World</.span>

Will output: <span data-phx-id="m3-phx-GBS__HJfKXiKyBHD">Hello World</span>

I don't know exactly what optimizations the doc is referring to, but to me, it already feels too implicit/ hard to track.


And it gets a little trickier because you can bypass the compiler warning with something like the following:

attr :class, :string, default: "foo"
slot :inner_block

defp span(assigns), do: ~H"<span class={@class}>{render_slot(@inner_block)}</span>"

Invoking it like this <.span class={if nil, do: nil}>Hello World</.span> also won't pick up the default value of the attr.

So, "nillish" values are handled in 3 different ways. Given that conditional logic with attrs is pretty common, should we try to make this more consistent for better DX?

  • Always empty attributes with nil unless it's a boolean attribute!?
  • Prevent compiler type checking attr when nil (unless attr is required)!?
  • Empty attr assign / use default value when nil is given to attr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant