DEV Community

Mykolas Mankevicius
Mykolas Mankevicius

Posted on

Phoenix LiveView is slot empty?

Here's a simple function to check if the slot is empty, where empty can mean.

  1. No slot provided
  2. Slot provided but has only whitespace
defp slot_empty?(slot) do
  case slot do
    [] ->
      true

    slots when is_list(slots) ->
      not Enum.any?(slots, fn slot ->
        case slot do
          %{inner_block: inner_block} when is_function(inner_block) ->
            inner_block.(%{}, nil)
            |> HTML.html_escape()
            |> HTML.safe_to_string()
            |> String.trim()
            |> Kernel.!=("")

          _ ->
            false
        end
      end)

    _ ->
      true
  end
end
Enter fullscreen mode Exit fullscreen mode

Example usage:

slot :inner_block

@spec heading(assigns :: map()) :: Rendered.t()
def heading(assigns) do
  ~H"""
  <header :if={not slot_empty?(@inner_block)} class="grid gap-4 pb-8 text-left">
    <%= render_slot(@inner_block) %>
  </header>
  """
end

Enter fullscreen mode Exit fullscreen mode

Hope this helps.

Top comments (0)