rhcarvalho
Is there an "else" to :if syntax in Heex templates?
Asking to get a sense of what other people are doing with their template logic…
The template code
I’m reading some third-party template code like this:
<li :if={message.role == :function_call} class="...">
...
<.icon_for_role role={message.role} />
...
</li>
<li :if={message.role != :function_call} class="...">
...
<.icon_for_role role={message.role} />
...
<.markdown :if={message.role == :assistant} text={message.content} />
<span :if={message.role != :assistant} >
...
</span>
...
</li>
In more than one occasion there’s a tag with an :if attribute immediately followed by a sibling tag with another :if that is the negation of the previous condition.
I realized a casual search of the docs for :if (Search for terms beginning with colon (e.g. ":if") · Issue #1820 · elixir-lang/ex_doc · GitHub) doesn’t work, but nonetheless found Components and HEEx — Phoenix v1.8.8. Docs and local code searches suggest there’s only :if and :for, no :else.
I wonder what other people are doing for cases like that? Repeating+negating conditions feels error prone to me.
How I think it should be written
I think <%= if %> ... <% else %> ... <% end %> would be more appropriate for template code like above? Or even <%= case %> and <%= cond %> for the more general cases?
I know JS frameworks like Vue have <tag v-if="condition">...</tag><tag v-else>...</tag>, but would not propose making Heex have even more ways to accomplish things that are already possible with existing syntax ![]()
What do you normally do in cases like that?
Most Liked
rhcarvalho
Yes, it is. And to this day the :if attribute doesn’t have an else counterpart, which is okay. My OP was trying to understand why people would use :if={cond} immediately followed by :if={!cond}, instead of using the older {%= if cond do %}...{% else %}...{% end %}.
I guess it’s just a matter of personal preference, sensibilities, style. No deep revelation ![]()
benregn
Edit: didn’t notice that you were talking about :if
knoebber
:unless={condition} would be a short hand for :if={!condition} , no previous clause needed. I’m only suggesting it because elixir already has it: Kernel — Elixir v1.16.3 (just not in heex).
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
- #code-sync
- #javascript
- #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









