1

I want to create a page in Phoenix that it would have links to all 'live' routes declared in the router.ex file. For example :

...
live "/", PageLive
live "/light", LightLive
live "/license", LicenseLive
live "/sales-dashboard", SalesDashboardLive
live "/search", SearchLive
live "/autocomplete", AutocompleteLive
live "/filter", FilterLive
live "/servers", ServersLive
....

I wanted to create a list with the routes in order to have the path links. Is there a way to get all exisiting live routes dynamically from phoenix router, without writing all again?

Something like mix phx.routes prints out.

1 Answers1

7

You can get a list of routes by using YourProjectWeb.Router.__routes__(). Notice that it's a private API and could change with a new phoenix version.

You can then filter based on the :plug field in the %Phoenix.Router.Route. For a live view, this has to be 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
  }
]
Jonas Dellinger
  • 1,294
  • 9
  • 19
  • Thanks. It solves the problem. I hoped for a standard reflection API, but I think his will do it! – GEORGE TARANTILS Jan 19 '21 at 18:35
  • 2
    Filtering and mapping the list to a map is what I used : ` MyProjectWeb.Router.__routes__() |> Stream.filter(fn r -> r.plug == Phoenix.LiveView.Plug end) |> Enum.map(fn r -> %{path: r.path, module: r.plug_opts} end)` – GEORGE TARANTILS Jan 20 '21 at 08:44