jaimeiniesta
Interpolating boolean attributes in HEEx
What is the proper way to interpolate boolean attributes like checked in an input in the new HEEx engine?
For example, in LEEx if I wanted to include it based on some condition, I would do this:
<input type="checkbox" name="web_pages[]" value="<%= w.id %>" <%= if w.id in @selected, do: "checked" %> />
Which would generate HTML like this:
<input type="checkbox" name="web_pages[]" value="1" />
<input type="checkbox" name="web_pages[]" value="2" checked />
Now in HEEx I do this
<input type="checkbox" name="web_pages[]" value={w.id} checked={if w.id in @selected, do: "true", else: nil} />
Which also works, if a nil value is passed then the checked attribute won’t be passed at all, but if I pass true then it will generate this:
<input type="checkbox" name="web_pages[]" value="2" checked="true" />
Which is correct, but longer and a bit uglier. I would have expected that this would work:
<input type="checkbox" name="web_pages[]" value={w.id} {if w.id in @selected, do: "checked"} />
But it doesn’t, it fails with protocol Enumerable not implemented for nil of type Atom. It looks like interpolation must always be bound to an attribute name in the HTML tag, right?
Marked As Solved
LostKobrakai
<input type="checkbox" checked={@boolean}> should just work.
Also Liked
jaimeiniesta
Ah! It does! The following works as expected, generating a valueless attribute for true or no attribute for false.
<input type="checkbox" name="web_pages[]" value={w.id} checked={w.id in @selected} />
Awesome, thanks!
LostKobrakai
I’ve no heex project at hand to check, but I’m quite confident it just generates a valueless attribute or no attribute.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #javascript
- #code-sync
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








