在 Phoenix 中组织 flash 消息

发布: (2026年5月1日 GMT+8 11:24)
3 分钟阅读
原文: Dev.to

Source: Dev.to

介绍

我开始构建一个系统,以更好地了解 Elixir 的工作方式,并学习 Phoenix

Phoenix 是 Elixir 的框架,就像 Rails 是 Ruby 的框架一样。它的使命是成为一个高效的框架,在不牺牲速度或可维护性的前提下提升生产力。

不再多说,我决定用 Elixir 构建一个简单的 CRUD 来记录我读过的书籍。我使用了以下命令:

# 创建应用。
$ mix phx.new booklistx

# 进入项目
cd booklistx

# CRUD 生成器(类似 Rails scaffold)
mix phx.gen.html Books Book books title:string

# 创建数据库和 books 表
mix ecto.create
mix ecto.migrate

我把书籍列表设为应用的根路径。

# 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

在 Phoenix 中组织 Flash 消息

我决定做一些类似于在 Rails 中的做法。
有很多解决方案(可能更好),但这种方法简单,并使用了我正在学习的概念。

创建的文件

# 创建 shared_view 文件
$ touch lib/booklistx_web/shared_view.ex

# 创建 shared 文件夹
$ mkdir -p lib/booklistx_web/templates/shared

# 创建 _flash_message.html.eex 文件
$ 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

这里我在 show_flash_message/1 中使用了管道操作符,并在 flash_message/1 中使用了模式匹配。

部分模板:lib/booklistx_web/templates/shared/_flash_message.html.eex

" role="alert">
  

布局: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.

参考资料

0 浏览
Back to Blog

相关文章

阅读更多 »

自己制作框架,有什么建议吗?

《Making my own framework》的封面图片。有什么建议吗?https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fde...