Specify html classes in heex

How would people convert the following code to heex?

  <%= for {flash_key, flash_message} <- @flash do %>
    <p class="alert alert-<%= flash_key %>" phx-click="lv:clear-flash">
      <%= flash_message %>
    </p>
  <% end %>

I guess I could do:

  <%= for {flash_key, flash_message} <- @flash do %>
    <p class={"alert alert-#{flash_key}"} phx-click="lv:clear-flash">
      <%= flash_message %>
    </p>
  <% end %>

But that seems kind of yuck too. Another potential solution, something like:

<%= for {flash_key, flash_message} <- @flash do %>
    <%
      classes =
        ["alert", "alert-#{flash_key}"]
        |> Enum.join(" ")
    %>
    <p class={classes} phx-click="lv:clear-flash">
      <%= flash_message %>
    </p>
  <% end %>

Still not sure I like it. Guess I could put the join in the function, not sure if that will help.

Just curious what other people would do in this situation, and what is considered good/acceptable.

This is considered the “right way” and how I do it. It seems much simpler in my opinion, than the other options you suggest, as it’s following the string interpolation rules more clearly and has no increase to your code (fits right there nicely in a short and sweet line).

If you want to extract all of the classes, then yea you could move your abstraction out into a classes function (you probably maybe want it somewhere else not right there in your same html file — probably you just want a custom css alert class at that point in your relevant css file). But, that’s definitely different than your original non-heex you present. :heart::blush:

2 Likes