Organizing flash messages in Phoenix
Source: Dev.to
Introduction
I started building a system to better understand how Elixir works and to learn about Phoenix.
Phoenix is a framework for Elixir, the same way Rails is a framework for Ruby. Its mission is to be a productive framework that doesn’t compromise on speed or maintainability.
Without further ado, I decided to build a simple CRUD in Elixir to track the books I’ve read. I used the following commands:
# Create the app.
$ mix phx.new booklistx
# Enter the project
cd booklistx
# CRUD generator (Rails scaffold style)
mix phx.gen.html Books Book books title:string
# Create the database and the books table
mix ecto.create
mix ecto.migrate
I set the books listing as the app’s root.
# lib/booklistx_web/router.ex
defmodule BooklistxWeb.Router do
use BooklistxWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", BooklistxWeb do
pipe_through :browser
# get "/", PageController, :index
end
end
Organizing Flash Messages in Phoenix
I decided to do something similar to what I’ve done in Rails.
There are many ways to solve this (probably better ones), but this approach is simple and uses concepts I’ve been studying.
Files Created
# Create shared_view file
$ touch lib/booklistx_web/shared_view.ex
# Create shared folder
$ mkdir -p lib/booklistx_web/templates/shared
# Create _flash_message.html.eex file
$ touch lib/booklistx_web/templates/shared/_flash_message.html.eex
lib/booklistx_web/shared_view.ex
defmodule BooklistxWeb.SharedView do
use BooklistxWeb, :view
import BooklistxWeb.Router.Helpers
def show_flash_message(conn) do
conn
|> get_flash()
|> flash_message()
end
def flash_message(%{"info" => message}) do
render("_flash_message.html", class: "primary", message: message)
end
def flash_message(%{"error" => message}) do
render("_flash_message.html", class: "danger", message: message)
end
def flash_message(_), do: nil
end
Here I’m using the pipe operator in show_flash_message/1 and pattern matching in flash_message/1.
Partial: lib/booklistx_web/templates/shared/_flash_message.html.eex
" role="alert">
Layout: lib/booklistx_web/templates/layout/app.html.eex
Booklistx · Phoenix Framework
"/>
- [Get Started](https://hexdocs.pm/phoenix/overview.html)
Feel free to leave feedback and suggest improvements.