Hide flash element if there is none?

The default template in the app.html.heex file is

<main class="container">
  <p class="alert alert-info" role="alert"><%= get_flash(@conn, :info) %></p>
  <p class="alert alert-danger" role="alert"><%= get_flash(@conn, :error) %></p>
  <%= @inner_content %>
</main>

but what if I want to put something else other than the p element like a group of elements and icons, how do I hide the element in case there is no flash alert?

2 Likes

I’d just not render anything if there’s no flash message to show. Imo the p:empty css phoenix uses is a clever way to handle no alerts, but also a bit to clever one.

I usually change this to something like this:

<%= for type <- [:info, :error], flash = get_flash(@conn, type) do %>
  …
<% end %>
4 Likes

It is clever but it brakes if you use mix format because it transform it into

<p class="alert alert-info" role="alert"><%= get_flash(@conn, :info) %></p>
</p>

instead of one line. Making p:empty selector to fail.

2 Likes

That’s what I mean by “to clever”. It’s just to fragile, now even more with the formatter breaking it even automatically.

1 Like
  # <.flash kind={:info} flash={@flash} />
  # <.flash kind={:error} flash={@flash} />
  def flash(%{kind: :info} = assigns) do
    ~H"""
    <%= if live_flash(@flash, @kind) do %>
      <div>...
    <% end %>
    """
  end
4 Likes