从phoenix router动态获取所有实时路由

GEO*_*ILS 2 elixir phoenix-framework phoenix-live-view

我想在 Phoenix 创建一个页面,它将链接到 router.ex 文件中声明的所有“实时”路由。例如 :

...
live "/", PageLive
live "/light", LightLive
live "/license", LicenseLive
live "/sales-dashboard", SalesDashboardLive
live "/search", SearchLive
live "/autocomplete", AutocompleteLive
live "/filter", FilterLive
live "/servers", ServersLive
....
Run Code Online (Sandbox Code Playgroud)

我想创建一个包含路线的列表,以便有路径链接。有没有办法从phoenix路由器动态获取所有现有的实时路由,而无需再次写入?

类似mix phx.routes打印出来的东西。

Jon*_*ger 8

您可以使用 获取路线列表YourProjectWeb.Router.__routes__()。请注意,它是一个私有 API,可能会随着新的 phoenix 版本而改变。

然后您可以根据:plug中的字段进行过滤%Phoenix.Router.Route。对于实时视图,这必须是Phoenix.LiveView.Plug

iex(18)> YourProjectWeb.Router.__routes__()
[
  %Phoenix.Router.Route{
    assigns: %{},
    helper: "login",
    host: nil,
    kind: :match,
    line: 2,
    metadata: %{log: :debug},
    path: "/login",
    pipe_through: [:browser],
    plug: YourProjectWeb.LoginController,
    plug_opts: :index,
    private: %{},
    trailing_slash?: false,
    verb: :get
  },
  %Phoenix.Router.Route{
    assigns: %{},
    helper: "settings",
    host: nil,
    kind: :match,
    line: 39,
    metadata: %{
      log: :debug,
      phoenix_live_view: {YourProjectWeb.SettingsLive, :index}
    },
    path: "/settings",
    pipe_through: [:browser, :ensure_authenticated],
    plug: Phoenix.LiveView.Plug,
    plug_opts: :index,
    private: %{
      phoenix_live_view: {YourProjectWeb.SettingsLive,
       [action: :index, router: YourProjectWeb.Router]}
    },
    trailing_slash?: false,
    verb: :get
  }
]
Run Code Online (Sandbox Code Playgroud)

  • 我使用的方法是过滤列表并将其映射到地图: ` MyProjectWeb.Router.__routes__() |> Stream.filter(fn r -> r.plug == Phoenix.LiveView.Plug end) |> Enum.map(fn r -> %{路径: r.path, 模块: r.plug_opts} end)` (2认同)