Search code examples
elixirphoenix-framework

How can I handle the empty case in Elixir/Phoenix templates?


In a template I have an iteration over some days in an itinerary:

<%= for day <- @days do %>
  <tr>
    <td><%= day.number %></td>
    <td><%= day.main_event_time %></td>
    <td><%= day.main_event %></td>
    <td><%= day.location %></td>
    <td><%= day.who %></td>
    <td><%= day.summary %></td>
    <td><%= day.lodging %></td>

    <td><%= link "Show", to: day_path(@conn, :show, day) %></td>
    <td><%= link "Edit", to: day_path(@conn, :edit, day) %></td>
    <td><%= link "Delete", to: day_path(@conn, :delete, day), method: :delete %></td>
  </tr>
<% end %>

I'd like have a different message come up in the case when there are no days yet. How can I do that?


Solution

  • With newer versions of Phoenix that support HEEx templates (v1.6 and greater), you can use the :if attribute to do this:

    <div :if={Enum.empty?(@days)}>
      No days yet.
    </div>