Check for error and info alert in Phoenix

In Rails we’re able to use

<% if info %>, however in Phoenix we don’t have that option, in the phoenix channel on Slack a guy pointed me to http://stackoverflow.com/questions/34068589/elixir-phoenix-flash-messages-do-not-show-up however it doesn’t work either, creating a file in /web/templates/layout/alert.html.eex with the content provided in the example throws an error:

Compiling 1 file (.ex)

== Compilation error on file web/views/layout_view.ex ==
** (CompileError) web/templates/layout/alert.html.eex:1: undefined function info/0
    (stdlib) lists.erl:1338: :lists.foreach/2
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:117: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/1

What is the way to do it correctly?

1 Like
<%= if get_flash(@conn, :info) do %>
  <span><%= get_flash(@conn, :info) %></span>
<% end %>

You can replace :info with whatever atom you specify in put_flash.

6 Likes

I have something like this. There is probably a much better way of doing it.

defmodule Learnp.LayoutView do
  use Learnp.Web, :view
  import Learnp.Router.Helpers

  def show_notification(conn) do
    conn
    |> get_flash
    |> flash_message
  end

  def flash_message(%{"info" => message}) do
    render "components/_notification.html", class: "primary", message: message
  end

  def flash_message(%{"error" => message}) do
    render "components/_notification.html", class: "danger", message: message
  end

  def flash_message(_), do: nil

end

And on my templates I can call it with <%= show_notification(@conn)%> and it will render the partial web/templates/layout/components/_notification.html.eex.

5 Likes

Please buddy, would you share the content of _notification.html.eex

It’s just some HTML with Bootstrap markup

<div class="callout <%= @class %>" data-closable>
  <button class="close-button" aria-label="Fechar alerta" type="button" data-close>
    <span aria-hidden="true">&times;</span>
  </button>
     <%= @message %>
</div>
3 Likes