Quick tip: Showing flash callouts in Phoenix with Foundation

Foundation is an awesome alternative to Bootstrap that comes pre-loaded into new Phoenix projects. It's a front-end framework makes it easy to lay in your own styles. On a recent project, I found that the way I was showing flash messages globally was pretty ugly:

<%= if get_flash(@conn, :info) do %>  
  <div class="callout primary"><p><%= get_flash(@conn, :info) %></p></div>
<% end %>  
<%= if get_flash(@conn, :error) do %>  
  <div class="callout alert"><p><%= get_flash(@conn, :error) %></p></div>
<% end %>  

I wanted to be able to output my flash messages in a single line without the repetition. Phoenix has the View layer which is perfect for building reusable components. By implementing a method in MyProject.LayoutView, I could create the flash callouts as easily as:

<%= flash_callout(@conn, :info, :primary) %>  
<%= flash_callout(@conn, :error, :alert) %>  

The flash_callout/3 method:

@doc """
Builds the Callout box for a specific key in the Flash.  
def flash_callout(conn, key, class \\ :info) do  
  if flash_message = get_flash(conn, key) do
    content_tag :div, class: "#{class} callout" do
      content_tag(:p, flash_message)

Dave Long

Read more posts by this author.

Subscribe to Dave Long

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!