Use if within ~H sigil

I have the following component and want to add bg-blue-100 as the class depending of the value of @is_active. I can’t find an example in Phoenix.Component — Phoenix LiveView v0.20.3 of how to do that. How can I?

  attr :is_active, :boolean, default: false, doc: "active state of the item"
  slot :inner_block

  def top_navigation_entry(assigns) do
    ~H"""
    <button
      type="button"
      class="bg-blue-100 relative text-xs text-brand-silver-900 font-medium flex flex-col items-center justify-center gap-1.5 py-3"
    >
      <%= render_slot(@inner_block) %>
    </button>
    """
  end
3 Likes

How does that work exactly? Seems like the actual output would be f.ex.

["bg-blue-100", "relative", nil, "flex", nil, "flex-col"]

…and then the code just does Enum.reject(classes, &is_nil/1), or?

class is special cased to concatinate the values in the list as you’d naively expect them to be concatinated.

concatenate[d]**

I see, so nil just gets converted to "", OK.

…and false too FWIW: Phoenix.Component — Phoenix LiveView v0.20.3

1 Like